How do you detect if Socket#close()
has been called on a socket on the remote side?
This question is related to
java
networking
sockets
tcp
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:
ServerSocket serverSocket = new ServerSocket(4444);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
while (true) {
out.println("output");
if (out.checkError()) System.out.println("ERROR writing data to socket !!!");
System.out.println(clientSocket.isConnected());
System.out.println(clientSocket.getInputStream().read());
// thread sleep ...
// break condition , close sockets and the like ...
}
The method Socket.Available will immediately throw a SocketException if the remote system has disconnected/closed the connection.
You can also check for socket output stream error while writing to client socket.
out.println(output);
if(out.checkError())
{
throw new Exception("Error transmitting data.");
}
Source: Stackoverflow.com