Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NIO - Detecting a closed connection

Tags:

java

tcp

nio

I have written a server that performs non-blocking IO using the Java NIO API. I'm seeing a situation whereby occassionally a client application shuts down abruptly (e.g. due to power loss) and the connection is left open on the server-side.

A colleague has encountered the same problem and said he uses heartbeats over the line to detect this kind of thing, but I'm hoping there's an easier way. Has anyone else encountered this problem?

Some additional information: My current server design will cancel a key and close the corresponding channel if it catches an IOException when attempting a read / write operation. This approach seems to work 99% of the time; I've only seen a handful of situations where the connection appears to be left open.

like image 637
Adamski Avatar asked Sep 30 '09 14:09

Adamski


1 Answers

Without app level heart-beats, your only option is to rely on TCP keepalive. But the default interval is very long (like 2 hours). The RFC doesn't recommend interval shorter than 2 hours.

You can make it shorter but this is a system-wide parameters. On some OS, it even requires kernel rebuild to change this.

Therefore, a heart-beat is highly recommended for any TCP-based protocol.

like image 69
ZZ Coder Avatar answered Oct 15 '22 06:10

ZZ Coder