javaclient-serversocketchanneldisconnection

Sending data to a client through a SocketChannel after he has closed his


I have a client and a server application where the client sends a byte of data that signals that the user has closed the client window and terminated the client program. The problem is that the server may send one last notification to that client before discarding him. If the server uses the SocketChannel's write method in blocking mode is it going to block indefinitely or is it simply ignored? Should I make the client wait for a "disconnection acknowledgement" before it is disconnected?


Solution

  • It won't block forever and it is not ignored. It is quite possible that it won't block at all, if there is room in the socket send buffer for the data. If it does block it may incur an IOException: 'connection reset by peer', or it may just unblock and return normally. There is no predicting this. The situation is incorrect and should not be allowed to occur. You can get to an agreed mutual close point by shutting down both sockets for output and then reading until you get an EOS; then both sides are at the same point and may close.