Search code examples
javanio

SocketChannel keeps reading -1


SocketChannel read keeps reading "-1" bytes which means end of stream by documentation.

in rox nio tutorial he says that

if (numRead == -1) {
  // Remote entity shut the socket down cleanly. Do the
  // same from our end and cancel the channel.
  key.channel().close();
  key.cancel();
  return;
}

But I am not sure he is right, can't it happen that the remote side sent me N bytes, waited 5 seconds (let's assume no timeouts) and then send me another M bytes.

Will I still get -1 while calling read() method? if so I wouldn't want to close the socketChannel and de-register it but rather wait for the next M bytes.

On the other hand, I keep getting numerous READ events from the selector which looks like a busy-wait.

What is the right approach in such case?


Solution

  • He is right. -1 means the peer has disconnected. There will never be any more data. You will not get -1 in the circumstance you mention.

    When you do get -1, you should close the channel. NB One thing he's wrong about is that closing the channel cancels the key: you don't need to do both.