Configure a Java Socket to fail-fast on disconnect?
-
09-06-2019 - |
Question
I have a listening port on my server that I'm connecting to using a Java class and the Socket
interface, i.e.
Socket mySocket = new Socket(host,port);
I then grab an OutputStream
, decorate with a PrintWriter
in autoflush mode and I'm laughing - except if the listening port closes. Then I get
tcp4 0 0 *.9999 *.* LISTEN
tcp 0 0 127.0.0.1.45737 127.0.0.1.9999 CLOSE_WAIT
and I can't seem to detect the problem in the program - I've tried using the isConnected()
method on the socket but it doesn't seem to know that the connection is closed.
I want to be aware of the problem the next time I try and write to the Socket so that I can try and reconnect and report the issue.
Any advice please?
Thanks all
Solution
Set a short timeout?
Does isOutputShutdown()
not get you what you want?
You could always build a SocketWatcher
class that spins up in its own Thread
and repeatedly tries to write empty strings to the Socket
until that raises a SocketClosedException
.
OTHER TIPS
The only reliable way to detect a broken connection in TCP is to write to it, which will eventually cause a 'connection reset' IOException. However due to buffering it won't happen on the first write after the disconnection,p but on a subsequent write. You can't do anything about this.
Set a different thread to reading from the socket. It will block until the socket is closed, and then an exception will be thrown. Catch that exception to detect the close immediately.