Java – NiO – detect closed connections

I wrote a server that uses Java NiO API to execute non - blocking io I see a situation where occasionally the client application suddenly shuts down (e.g. due to power failure) and the connection remains open on the server side

A colleague encountered the same problem and said he used heartbeat to detect such things, but I hope there is a simpler method Has anyone else encountered this problem?

Some additional information: my current server design will cancel the key and close the corresponding channel when I catch IOException when trying to read / write This approach seems to work 99% of the time; I only see some connections that seem to remain open

Solution

If there is no app level heartbeat, your only choice is to rely on TCP keepalive But the default interval is very long (such as 2 hours) RFC does not recommend an interval of less than 2 hours

You can shorten it, but this is a system wide parameter On some operating systems, it even requires a kernel rebuild to change it

Therefore, heartbeat is strongly recommended for any TCP - based protocol

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>