java:通过套接字发送大文件

tjjdgumg  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(232)

所以我在做一个基于客户机-服务器的架构程序,服务器发送一个文件,客户机接收它。我看到了很多代码部分,我也做了很多我发送小文件的地方。ex图像。在我的情况下,我想发送.wav音频文件是大(40mb)。这就是我到目前为止所做的。当我运行我的客户机时,它只是继续下载,但从来没有真正下载文件。我想是因为太大了。
怎么发送这么大的文件?
服务器

public void send_file_to_client(String requested_file) throws IOException {
        FileInputStream fis = null;
        BufferedInputStream bis = null;

        File FILE_TO_SEND = new File("C:\\ServerMusicStorage\\" + requested_file + ".wav");
        byte[] mybytearray = new byte[(int) FILE_TO_SEND.length()];
        try {
            fis = new FileInputStream(FILE_TO_SEND);
            bis = new BufferedInputStream(fis);

        } catch (FileNotFoundException ex) {
            Logger.getLogger(ClientHandler.class.getName()).log(Level.SEVERE, null, ex);
        }

        OutputStream os = null;
        bis.read(mybytearray, 0, mybytearray.length);
        os = connsock.getOutputStream();
        System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");

        toClient.writeUTF(Integer.toString(mybytearray.length));
        os.write(mybytearray, 0, mybytearray.length);
        os.flush();
        System.out.println("Done.");

        if (bis != null) {
            bis.close();
        }
        if (os != null) {
            os.close();
        }
        if (connsock != null) {
            connsock.close();
        }
    }

客户

public static void receive_file(String requested_file) throws IOException {

        File file_to_save = new File("C:\\ClientMusicStorage\\" + requested_file + ".wav");
        int bytesRead;
        int current = 0;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;

        //get file size to create the bytearray
        String fileSize=fromServer.readUTF();
        int final_file_size = Integer.parseInt(fileSize);

        byte[] mybytearray = new byte[final_file_size];
        InputStream is = clientSocket.getInputStream();
        fos = new FileOutputStream(file_to_save);
        bos = new BufferedOutputStream(fos);
        bytesRead = is.read(mybytearray, 0, mybytearray.length);
        current = bytesRead;

        do {
            bytesRead
                    = is.read(mybytearray, current, (mybytearray.length - current));
            if (bytesRead >= 0) {
                current += bytesRead;
            }
        } while (bytesRead > -1);

        bos.write(mybytearray, 0, current);
        bos.flush();
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题