Search code examples
javacsocketsansi-c

Read all bytes from socket Stops at 52964 bytes


I'm making a Server that gets packages at 64 kb size.

        int length = 65536;
        byte[] bytes = new byte[length];

        int pos = 0;
        while(pos < length -1)
        {
            System.out.println("Before read");
            pos += dis.read(bytes, pos, length-pos);
            System.out.println(""+pos+" >> "+ length);
        }

This is the code I use to read all bytes from the socket. Dis is a InputStream. When I run the code 1 out of n goes wrong. The code only receives 52964 bytes instead of 65536 bytes.

I also checked the C code and it says it send 65536 bytes.

Does someone know what I'm doing wrong?


Solution

  • This is yet another case where Jakarta Commons IOUtils is a better choice than writing it yourself. It's one line of code, and it's fully tested. I recommend IOUtils.readFully() in this case.

    If it does not read the entire buffer, then you know that you're not sending all the content. Perhaps you're missing a flush on the server side.