Java nio Reading SocketChannel on a Selector
-
21-06-2021 - |
Question
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
Solution
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.