tags:

views:

2361

answers:

3

Hey all. I have a server written in java using the ServerSocket and Socket classes.

I want to be able to detect and handle disconnects, and then reconnect a new client if necessary.

What is the proper procedure to detect client disconnections, close the socket, and then accept new clients?

+4  A: 

Presumably, you're reading from the socket, perhaps using a wrapper over the input stream, such as a BufferedReader. In this case, you can detect the end-of-stream when the corresponding read operation returns -1 (for raw read() calls), or null (for readLine() calls).

Certain operations will cause a SocketException when performed on a closed socket, which you will also need to deal with appropriately.

Rob
A: 

The sun page is down (or i just can't access it) so i can't confirm it, but if i remember correctly just need to do this

(...)
(Your code here)
} catch (SocketException e) {
 tryToConnect() // This is your code to try to connect, not an inbuilt function.
}
fmsf
A: 

The only safe way to detect the other end has gone is to send heartbeats periodically and have the other end to timeout based on a lack of a heartbeat.

Peter Lawrey
Or you could just set the timeout
Pyrolistical
I have a thread which looks at each connection to see how long it has been since the last packet was read. (heartbeat or otherwise)It it has been too long, I close the connection.
Peter Lawrey