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?
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 aSocketException(“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:
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)