Sign in to follow this  
HelloSkitty

Checking if a Connection Socket Is Dead

Recommended Posts

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:

[CODE]
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
[/CODE]

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).

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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... Edited by Xanather

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this