Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a Socket is currently connected in Java? [duplicate]

Tags:

java

tcp

sockets

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.

like image 330
Supertux Avatar asked Sep 07 '09 16:09

Supertux


People also ask

How can I tell if a socket is running?

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.

How do you know if a socket is closed?

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.


2 Answers

  • socket.isConnected() returns always true once the client connects (and even after the disconnect) weird !!
  • socket.getInputStream().read()
    • makes the thread wait for input as long as the client is connected and therefore makes your program not do anything - except if you get some input
    • returns -1 if the client disconnected
  • socket.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.

like image 137
Sumit Singh Avatar answered Oct 13 '22 09:10

Sumit Singh


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.

like image 30
Jason Nichols Avatar answered Oct 13 '22 07:10

Jason Nichols