Can't send large files over socket in Java

前端 未结 5 1642
执念已碎
执念已碎 2021-01-14 06:51

I got working server and client applications, they work perfect while sending small files, but when I try to send for example movie file that is 700mb over socket it gives m

5条回答
  •  无人及你
    2021-01-14 06:57

    The problem is that you are trying to load the entire file at once into memory (via readFully), which exceeds your heap space (which by default is 256mb I think).

    You have two options:

    1. Good option: load the file in chunks (e.g. 1024 bytes at a time) and send it like that. Takes a bit more effort to implement.
    2. Bad option: increase your heap space via -Xmx option. Not recommended, I mostly mentioned this just in case you will need a bit more heap space for a program, but in this case it's a really bad idea.

    For option one you can try something like:

    DataInputStream in = new DataInputStream(new FileInputStream("file.txt"));
    byte[] arr = new byte[1024];
    try {
        int len = 0;
        while((len = in.read(arr)) != -1)
        {
            // send the first len bytes of arr over socket.
        } 
    } catch(IOException ex) {
        ex.printStackTrace();
    }
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题