views:

202

answers:

4

I use a Java Socket object in my client application. I need to know when the line to the server is broken, or if any event caused the socket to be dead.

I see two methods:

  • catching SocketException when writing in or reading from the socket, considering these exceptions kill the socket
  • when catching these exceptions, checking the Socket.isClosed() method to know if it killed the socket

Does any of these methods guarantee I'll know when the socket is dead and won't work again, even if a temporary problem on the line is solved? Can we except a (Socket)Exception thrown during an operation on a socket to imply the socket is dead?

Is there a better method to know this?

A: 

A "Dead Socket" can be considered as an abnormal status. It is just a errornous bahaviour. So I don't think you can handle this situation effectively.

Chathuranga Chandrasekara
A: 

This is usually done by a timeout. This is mandatory if you don't trust the other side (like every time). Without a timeout, an attacker can DoS your application easily by opening connections without sending anything. Once you hit the socket limit of your system, the application might even crash...

oeogijjowefi
+1  A: 

At least:

  1. Receiving an exception does NOT mean the socket is always dead, from Socket.setSoTimeout() javadoc:

    If the timeout expires [on a read for instance, a java.net.SocketTimeoutException is raised, though the Socket is still valid.

  2. The closed flag of the socket seems to be set only when the Socket.close() method is called, so I would not rely on it.

penpen
A: 

Since there is nothing like a keep-alive between sockets, you will learn that the connection is broken not until ,next time you try to write onto this socket.

stacker