This question already has an answer here:
How do you detect if Socket#close()
has been called on a socket on the remote side?
This question already has an answer here:
How do you detect if Socket#close()
has been called on a socket on the remote side?
Since the answers deviate I decided to test this and post the result - including the test example.
The server here just writes data to a client and does not expect any input.
The server:
The
isConnected
method won't help, it will returntrue
even if the remote side has closed the socket. Try this:Start the server, start the client. You'll see that it prints "connected: true" twice, even though the socket is closed the second time.
The only way to really find out is by reading (you'll get -1 as return value) or writing (an
IOException
(broken pipe) will be thrown) on the associated Input/OutputStreams.You can also check for socket output stream error while writing to client socket.
The method Socket.Available will immediately throw a SocketException if the remote system has disconnected/closed the connection.