简体   繁体   中英

Java nio Reading SocketChannel on a Selector

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM