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:
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.