I have a question with reference to this tutorial
In the read method of the server, if read returns -1 then does it always mean client has closed connection??
I modified the example client to sleep for long time after sending the message I see that the selector.select() does not block and keeps selecting the channel as readable even if client is not sending anything and server reads method reads and returns -1, and thus closes the channel, but the client has not disconnected.
I do not understand this behavior. Can some one help me understand?
I am trying to modify the server so that the server does not disconnect with client even if client is not sending anything and so it must block at selector.select().
In the read method of the server if read returns -1 then does it always mean client has closed connection?
server reads method reads and returns -1 , and thus closes the channel , but the client has not disconnected.
Yes it has. That's what it means. The client has closed the connection.
The API should work as described. Read will return -1 when the socket connection is closed. This is not the same as "end of message". A connection can be closed by a time-out and I note that you said you had the client wait for "a long time".
I also note that you are working from a specific tutorial. The client code in that tutorial specifically closes the connection after receiving a response and opens a new one for every send. You would have to make large changes to the client code design to stop this.
When I run the nio server from that tutorial with a client that does not close the connection, the behaviour is as the API describes - the server thread waits in Selector.select() whilst the client sleeps between sending messages.
My answer is hence that you are probably using a client that is closing connections, and if not the "long time" you are waiting could cause the network to close the connections for you. Given the behaviour you describe I am pretty sure it is the former.
I guess - but I am not really sure, cause I didn't read it completely - you fail in the distinction between Port-connection and Socket-connection. To my understanding the connection is opened via a socket on a specific port. The socket could be closed resp. received the end of the message which was sent - but the connection could still remain.
To my understanding -1 indicates the end of the messages sent via the socket-connection. There is no clear indicator which tells you directly the connection is closed.... You have to invent it by yourself. (My 2cents of understanding.)