简体   繁体   中英

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?

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.

InputStream.read() returns the number of bytes read or -1 if the end of the stream has been reached. You need to check for that error condition. Also, I suspect your while(..) loop is the problem. Why are you calling it pos as in position? You may be terminating prematurely. Also, ensure that your C code, whatever it is doing, is sending properly. You can examine the network traffic with a tool like Wireshark to be sure.

What do you mean it "goes wrong"? What is the output? It can't be exiting the loop before reading the full 64 KB, so what really happens?

Also, it's better to save the return value of the I/O call separately and inspect it, before assuming the I/O was successful. If that's DataInputStream.read() , it returns -1 on error.

Your code is incorrect as it doesn't check for -1.

This is a case for using DataInputStream.readFully() rather than coding it yourself and getting it wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM