I have an NIO Socket Server "S1".
I have an NIO Socket Client thread T1 having reference to a valid socket channel connected to "S1"
S1 sends messages to T1 say of 100 bytes each in an infinite loop.
T1 runs in an infinite loop & has a read() method which reads from the socket channel when the Selector registered with it receives an OP_READ key. After each successful read thread T1 sleeps for 5 seconds.
Here are some questions looking to be answered:
1.) What happens to the messages sent by S1 when thread T1 is sleeping ?
2.) Does the Selector registered with the Socket Channel buffer the messages irrespective of the fact that T1 is sleeping ?
3.) If answer to 2.) is YES then what happens when Server S1 has sent say 500 bytes while T1 was sleeping and then S1 disconnects due to some IOException before T1 wakes up. Have those 500 bytes sent by S1 before disconnecting been received and buffered by the Selector?
If they have been received and buffered then is it possible to retrieve them?
one key concept in NIO socket is non blocking i/o. this means that you don't do a blocking read or write.
you only need to register with the selector once.
the 3) one is a bit tricky. i am not 100% sure.
Joined: Jun 10, 2008
I performed some tests and found that on reading from the socket channel after sleeping for 5 seconds i am successful in reading the buffered messages if the socket channel is connected.
If the socket channel is disconnected when Thread T1 was asleep then on waking up T1 gets an IOException on attempting to read from the socket channel even though the Server S1 had sent some messages to T1 before closing the connection.
Is there any way of retrieving those messages which Server S1 had successfully sent before going down and which T1 was not able to capture as it was [asleep]/[runnable state]/[processing something else]?
Joined: Dec 11, 2008
while T1 is asleep, someone on the T1 side must be processing the incoming the incoming tcp packets. otherwises, these packets won't be acked and stored on the T1 side. So whoever process these on the T1 side on the different thread need to store these messages somewhere else. this can be abstract. without seeing your code, this is the best i can suggest.
Joined: Jun 10, 2008
Thanks luri for your reply.
Actually i've figured the problem is not related to NIO sockets but how TCP/IP sockets work.
The other process that you are talking about is the TCP/IP stack of my OS which takes care of buffering the data sent by the server which can be fetched even after there is a graceful close of the socket connection done by the server. In case of a sudden network failure the data cannot be fetched as it is discarded by the TCP receive buffers immediately on receipt of a RST coding bit in the TCP segment.
subject: Please verify if i understand NIO Selectors