1

I have a small server application which receives connections from multiple clients. The clients will connect, send a message and disconnect, there is no response sent back.

I'm using a ServerSocketChannel to listen for connections. I get notified of new connections using a selector, When this happens I register the SocketChannel with the selector for SelectionKey.OP_READ

The part I'm unsure of is when I get notified data is available for reading. My SocketChannels are in nonblocking mode. I call channel.read(buffer) on the SocketChannel to read into the byte buffer From the javadoc for read, I should repeatadly call this until I get a -1 indicating the end of the stream. However, I'm not sure if I should be waiting for the selector to notify me again before calling read again. That is:

  • I get notified by the selector that data is available.
  • I call read
  • Should I then call read again until -1 is returned or should I let the selector notify me then call read again

Many Thanks

jasg
  • 182
  • 2
  • 10

1 Answers1

3

From the javadoc for read, I should repeatadly call this until I get a -1 indicating the end of the stream.

It doesn't say any such thing.

If you're in non-blocking mode, you can read until it returns -1 or zero. If it returns zero, there is no more data pending in your socket receive buffer, so you should return to the select loop. If it returns -1, that's it, finished, done, finito, close the socket channel and proceed accordingly.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Thanks, yes the javadoc does not say that, but some tutorials on the net do. What you've written makes perfect sense. – jasg Jul 18 '12 at 11:02
  • @jasg Most tutorials on the net are garbage, and particularly the NIO ones. Stick to the ones on the Oracle site. They're not perfect, but at least they've been QA'd and reviewed; they come from the right source; and there is a bug reporting system for them. The IBM ones are generally first rate as well. Avoid blogs, interview question sites, and anything unrefereed and unreviewed like the plague. – user207421 Jul 18 '12 at 23:38