How to Know Java Socket is Dead

I am using a Java Socket object in my client application. I need to know when the string on the server is broken, or if any event caused a socket leak.

I see two methods:

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

Does any of these methods guarantee that the socket will be dead and will not work again, even if the temporary problem on the line is resolved? Can we throw a Socket exception during a socket operation to suggest that the socket is dead?

Is there a better way to find out?

+3
source share
4 answers

At least:

  • Getting an exception does NOT mean that the socket is always dead, from Socket.setSoTimeout()javadoc:

    If the timeout expires [when reading, for example, a java.net.SocketTimeoutException is thrown, although Socket is still valid.

  • A closed socket flag, apparently, is set only when the method is called Socket.close(), so I will not rely on it.

+2
source

This is usually done with a timeout. This is mandatory if you do not trust the other side (for example, every time). Without a timeout, an attacker can easily execute your application by opening connections without sending anything. As soon as you click the restriction on the socket of your system, the application may even crash ...

+1
source

A "Dead Socket" . . , .

0
source

Since there is nothing like keep-alive between sockets, you will find out that the connection is interrupted until the next time you try to write this socket.

0
source

Source: https://habr.com/ru/post/1728273/


All Articles