当前位置: 动力学知识库 > 问答 > 编程问答 >

java nio: if read returns -1 does it mean client has closed connection?

问题描述:

I have a question with reference to this tutorial

http://rox-xmlrpc.sourceforge.net/niotut/

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().

thank you!

网友答案:

In the read method of the server if read returns -1 then does it always mean client has closed connection?

Yes. Always.

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: