tags:

views:

1233

answers:

3

Hi,

I'm trying to find out whether a Java TCP Socket is currently connected, the following just seems to tell me whether the socket has been connected at some point - not whether it is currently still connected.

socket.isConnected();

Any help appreciated, thanks.

+1  A: 

You can also use isClosed() method which chcecks if socket is closed. But as far as i remember using isConnected() should do the work.

pir0
+1  A: 

See this thread for a discussion. Essence: Use setKeepAlive() or else send something and see if you get an EOF indication.

Peter Arrenbrecht
+1  A: 

Assuming you have some level of control over the protocol, I'm a big fan of sending heartbeats to verify that a connection is active. It's proven to be the most fail proof method and will often give you the quickest notification when a connection has been broken.

TCP keepalives will work, but what if the remote host is suddenly powered off? TCP can take a long time to timeout. On the other hand, if you have logic in your app that expects a heartbeat reply every x seconds, the first time you don't get them you know the connection no longer works, either by a network or a server issue on the remote side.

See http://stackoverflow.com/questions/865987/do-i-need-to-heartbeat-to-keep-a-tcp-connection-open for more discussion.

Jason Nichols