简体   繁体   中英

read 19000 bytes from java socket(TCP)

this is my simplified code

sock.getOutputStream().write(buff); //send a readRequest
byte[] rbuff = new byte[19210]; //Answer has 19210 bytes of data
sock.getInputStream().read(rbuff);

In wireshark I see that it is splitted in a few tcp packages. But shouldn't the read wait as long as 19210 byte have arrived?

I get the data, but from a certain position all bytes are 0. This is mostly the same position but varies a bit.

Any idea what I do wrong here?

You can try to read it in chunks like this:

ByteArrayOutputStream b= new ByteArrayOutputStream();

byte[] buf = new byte[1024];
while (count = in.read(buf)) > 0)
{
  b.write(buf,0,n);
}

byte data[] = b.toByteArray();

Simply study the Javadoc for Inputstream.read() :

"Reads some number of bytes from the input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer."

Meaning: read() does not wait until it has enough bytes to fill the buffer. It is already happy when it could fill some of the bytes. Thus you have to check the number that is returned; and loop until you collected all the bytes you need. In other words: don't provide a buffer of size 19K; use a smaller one; and "copy" over the bytes you received into another data structure.

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