DataInputStream.read returns less than len

I am using DataInputStream to read multiple bytes from a socket. I have the expected number of bytes to read from the stream (after decoding the header, I know how many bytes are in the message). It works 99% of the time, but sometimes I will have the number of bytes read less than len.

int numRead = dis.read(buffer, 0, len);

What can cause numRead to be less than len? This is not -1. I would expect that the reading behavior will be blocked until the stream is closed or EOF is reached, but if this is the socket underlying the threads, this should not happen if the socket does not close, right?

Is there a way to read bytes from a socket that always ensures that you are reading len bytes?

thank

+3
source share
4

EDIT: , , , . DataInput (, DataInputStream) readFully, . , , InputStream.

, InputStream , , . - , , ByteArrayInputStream. ( , , , , .)

, :

byte[] data = new byte[messageSize];
int totalRead = 0;

while (totalRead < messageSize) {
    int bytesRead = stream.read(data, totalRead, messageSize - totalRead);
    if (bytesRead < 0) {
        // Change behaviour if this isn't an error condition
        throw new IOException("Data stream ended prematurely");
    }
    totalRead += bytesRead;
}
+10

DataInputStream .

byte[] bytes = new byte[len];
dis.readFully(bytes);

, IOException.

+7

read , , -1, ,

while (true) {
  int numRead = dis.read(buffer, 0, len);
  if (numRead == -1) break;
  total.append(buffer, numRead);
}
0

, , EOF .

Javadocs. read() , , , , EOS . , , . .

0

Source: https://habr.com/ru/post/1785069/


All Articles