devxlogo

Unexpected Socket Close

Unexpected Socket Close

Question:
How do you determine when a client has closed its socket, so that aserver can cease to wait for messages from that client?

Answer:
When a socket endpoint closes its socket, a read on the InputStreamat the other end will return -1, indicating end of file. If theprocess crashes, the same will happen because the operating systemwill close the socket when the process dies.

However, if the hostthat the process is running on crashes, there is no way to detectthe endpoint termination. With native system programming, it ispossible to set the SO_KEEPALIVE socket option to test the integrityof a connection on a more frequent basis than the default 2 hours.Java does not allow you to do this, and instead relies on the systemdefault.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist