Checking if a Connection Socket Is Dead

Started by
1 comment, last by Xanather 11 years, 8 months ago
I'm currently have a Server program running with multiple sockets, which I'm testing with netcat. So I run the server, which makes a bunch of client handlers -- one for each client, and associates a socket with each. I have an infinite while loop running through and updating these handlers, and in the update code, I have this:


if (!socket.isConnected()) {
System.out.println("CONNECTION DROPPED");
server.handlers.remove(this);
}
if (socket.isInputShutdown()) {
System.out.println("INPUT SHUTDOWN");
}
if (socket.isOutputShutdown()) {
System.out.println("OUTPUT SHUTDOWN");
}
if (!socket.isBound()) {
System.out.println("NOT BOUND");
} //4 methods I found in the java doc for the Socket clas


So I have 4 if statements that presumably check if a socket is shut down. Unfortunately, when I kill one of my netcat test client instances, none of these if statements return a positive. Am I using these functions wrong, or is there some other function that achieves the purpose I seek?

I know that it must be possible to detect a dropped connection, as when I kill the server, all of my netcat clients know this and cease their function. I just can't seem to detect when a Client dies.

For those who aren't familiar with netcat, all it is is a simple program that can send messages across ports (at least, I think that's all it is).
A penny for my thoughts? Do you think I have only half a brain?

Not-so-proud owner of blog: http://agathokakologicalartolater.wordpress.com/
Advertisement
Generally speaking you have to attempt to do some IO on the socket before you can detect a dropped connection. Try setting it up so that your clients send a small "heartbeat" packet to the server every, say, 30 seconds. If you don't get a heartbeat for over a minute, you can assume the connection has dropped.

As a bonus, if your connection is closed normally, attempting IO will immediately return an error instead of forcing you to wait a time interval to detect a missing heartbeat.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

You could do what Apoch has mentioned, but you could also use the "heart beat" messages to display current latency towards the server.

If you are using TCP just attempt to read/write from the network, if a IO error returns/exception is thrown then you can safely assume the connection has closed. UDP wont work like that though as it is connectionless...

This topic is closed to new replies.

Advertisement