I am writing a Java client/server program using Socket and ServerSocket. Multiple clients connect to the server at once. What is the best way to check if a client connection has disconnected from the server side? Right now, I'm just getting a SocketException when attempting to write to a disconnected client.
Asked
Active
Viewed 2,173 times
2
-
this question will help you: http://stackoverflow.com/questions/698964/checking-if-a-clientsocket-has-disconnected-in-java-hangs – Adi Sembiring Apr 10 '11 at 00:29
-
The `SocketException` tells you that *you* have *already* closed the socket. It indicates a logic bug in your application. The way to *detect* a closed connection, rather than ignoring it as you are now, is by `read()` returning -1 or `write()` throwing an `IOException`. – user207421 Jun 11 '21 at 06:20
1 Answers
1
The best way to detect a disconnection is to have the other end send a heartbeat and have the reader timeout when there is no data.

Peter Lawrey
- 525,659
- 79
- 751
- 1,130
-
Just to clarify, who would be sending the heartbeats? The server or the clients? – meteoritepanama Apr 09 '11 at 19:01
-
1The writer sends the heartbeats, the reader expects them. It doesn't matter which end is the client or server. – Peter Lawrey Apr 09 '11 at 22:05
-
@PeterLawrey how can we assume there is a proper disconnect from the client end to apply heartbeat call... there might be an interruption that breaks socket connection... I would want to detect and do change appropriate change for particular user. – Sathish Sep 03 '18 at 14:34
-
@Sathish You detect it by the hearbeat write failing, or not being received. – user207421 Nov 13 '19 at 08:46