Cheetah
Cheetah

Reputation: 14449

Server detecting a client losing connection from the socket

In Java, if I connect to a client to a server via a socket and the client has an exception which causes it to crash, is there any way the server can detect that the socket connection is lost.

I assume one method would be have some sort of heartbeat polling the client, but is there a simpler/easier way?

Upvotes: 1

Views: 10986

Answers (2)

SimonJ
SimonJ

Reputation: 21306

There are a few ways, depending on what you consider to be a "crash".

If the client process dies, the client OS will close the socket. The server can detect this by performing a read(), which will either return -1 (EOF) or raise a SocketException ("connection reset").

If the client gets into an infinite loop, the connection will remain open; the only way to detect this is by incorporating some kind of "heartbeat" into your protocol.

If the client host is rebooted or the network connection breaks, the server may not notice unless either:

  • the protocol has a "heartbeat" mechanism as above, with some kind of timeout, or
  • TCP keepalive is enabled on the socket by calling socket.setKeepAlive(true) - this instructs the OS to periodically* send a packet to check that the remote end of the connection is alive, closing the connection if not

*both Windows and Linux default to 2 hours; you can change this system-wide but not per-socket (under Java, anyway)

Upvotes: 4

Chris Dennett
Chris Dennett

Reputation: 22741

TCP sockets do this anyway, and Java exposes it to the developer. See setKeepAlive() / getKeepAlive() in the Socket class. If a TCP message isn't sent from the client to the server for a certain period of time, the socket will close, and the server can remove the session information because it still has its endpoint.

Upvotes: 0

Related Questions