user3313539
user3313539

Reputation: 133

Detecting TCP drop out?

Currently the way I detect if a client has crashed is if an exception occurs when listening for communications. I assume this is because if the client crashes then the OS will close the socket. Will an exception still fire if if the client's internet drops out or they shutdown their PC? If not what is the best way of handling disconnections like this? Thanks.

Upvotes: 1

Views: 827

Answers (3)

Warren Dew
Warren Dew

Reputation: 8938

TCP is designed to maintain a connection indefinitely even when no data is moving across the connection in either direction. This means that the connection will not close and you will not see an exception if the client's network or an intermediate network goes down - and in fact, if such a network goes down, and then later comes back up, even hours later, a TCP connection that was unused during that period will by default still be there and usable for further communications afterwards. You will also not get an exception if the client computer crashes or is abruptly powered off. You might get an exception if the client computer is shut down normally, since its shutdown process might include closing all connections, depending on the operating system.

If you want to disconnect when the network is lost for a certain period or when the client crashes, usually the best way to do it is by setting TCP keepalive. In Java, you can enable TCP keepalive by calling Socket.setKeepalive(true). This causes your socket to send occasional probe packets to check if the other end of the connection is still alive.

Note that the default interval between TCP keepalive checks is typically two hours, and it is typically a system wide property. If you want the interval to be less, you'll need to change the system configuration.

Upvotes: 4

Kakarot
Kakarot

Reputation: 4252

Usually there is a way to specify the timeout for every operation that you are performing cia TCP/UDP Connections. So if no response(message or ACK) is received from the client for sometime the socket would throw a SocketTimeoutException.

For example

1) socket.connect(otherAddress, timeout)

2) socket.setSoTimeout(timeout) for setting a timeout on read() operations.

Upvotes: 0

user3343927
user3343927

Reputation: 103

socket timeouts are quite long and OS/implementation dependents. you need to do something active like pinging your client at regular intervals to see if it's still alive (or any over type of query that the client can answer depending on what type of communication you are using)

Upvotes: 0

Related Questions