0
votes

As the title says, could DataInputStream.read() override previously read bytes if there are more bytes available than the size of buffer, if in the first read some bytes were missed ?

There are fixed size packets exchanged between peers, and it is possible that two packets are available at the Socket. Let's say that size of one packet is 500, and there are two packets of total size 1000 available at the socket. Additionally, let's say that read fetches 400 bytes out of available 1000.

  • Is it even possible that read() doesn't read all 500 bytes if they are available ?

  • What will happen when read is invoked again, is it possible that more than 100 bytes are read ?

It is not really clear to me what happens in that case given the javadoc:

The first byte read is stored into element b[0], the next one into b[1], and so on. The number of bytes read is, at most, equal to the length of b.

I would like to know if below block of code should be modified as shown in comment to read only one packet fully.

    while ((readBytes = stream.read(buffer)) != -1) {

        totalBytes += readBytes;

        if (totalBytes < buffer.length) { // must this be != instead of < ?

            continue;
        }

        // all bytes are available
        else {

            break;
        }
1
Your example is unclear - you talk about one packet of size 500, and two packets of size 1000, with only two packets in total.Jon Skeet
I mean, there are 1000 bytes available before read. Buffer is of size 500 and i would like to read only 500 belonging to first packet. Buffer is byte[] passed to read method.John
I am not even sure if such situation is possible. Since it's not clear to me will read pick up all bytes available at the point of reading.John
And how big is the buffer? Basically it's all still somewhat confused at the moment...Jon Skeet
(You may want to use readFully instead of read...)Jon Skeet

1 Answers

1
votes

Each time you call read(byte[]), it will:

  • Block until at least one byte is read from the input, or the input is closed
  • Copy bytes from the input into the array, starting at index 0 of the array
  • Return when there are no more bytes available (typically, anyway - it could have some delay where it waits a while for more to become available)

There's no memory of previous read calls - it won't start writing into the array at the previous index. If you want that behaviour, you need to write it yourself:

byte[] buffer = new byte[500];
int totalRead = 0;
while (totalRead < buffer.length) {
    // Pass in an offset and length, so we can keep reading into the
    // next part of the array.
    int bytesRead = input.read(buffer, totalRead, buffer.length - totalRead);
    if (bytesRead == -1) {
        throw new EOFException(); // Or whatever... stream ended early
    }
    totalRead += bytesRead;
}

... or call readFully() which will basically do the same thing.