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.
A socket is 'running' until you close it. However the connection to which it is an endpoint may be dropped, and this is signalled by errors when reading or writing, or end of stream when reading. There is no other test in TCP or UDP.
You could check if the socket is still connected by trying to write to the file descriptor for each socket. Then if the return value of the write is -1 or if errno = EPIPE, you know that socket has been closed.
socket.isConnected()
returns always true once the client connects (and even after the disconnect) weird !!socket.getInputStream().read()
returns -1
if the client disconnectedsocket.getInetAddress().isReachable(int timeout)
: From isReachable(int timeout) Test whether that address is reachable. Best effort is made by the implementation to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.
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 Do I need to heartbeat to keep a TCP connection open? for more discussion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With