<p>I have a listening port on my server that I'm connecting to using a Java class and the <code>Socket</code> interface, i.e.</p>

<pre><code>Socket mySocket = new Socket(host,port);
</code></pre>

<p>I then grab an <code>OutputStream</code>, decorate with a <code>PrintWriter</code> in autoflush mode and I'm laughing - except if the listening port closes. Then I get </p>

<pre><code>tcp4       0      0  *.9999                 *.*                    LISTEN
tcp        0      0  127.0.0.1.45737        127.0.0.1.9999         CLOSE_WAIT
</code></pre>

<p>and I can't seem to detect the problem in the program - I've tried using the <code>isConnected()</code> method on the socket but it doesn't seem to know that the connection is closed.</p>

<p>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.</p>

<p>Any advice please?</p>

<p>Thanks all</p>

[{'answer_id': 22803, 'author': 'James A. Rosen', 'author_id': 1190, 'author_profile': 'https://Stackoverflow.com/users/1190', 'pm_score': 2, 'selected': True, 'text': '<p>Set a short timeout?</p>\n\n<p>Does <code>isOutputShutdown()</code> not get you what you want?</p>\n\n<p>You could always build a <code>SocketWatcher</code> class that spins up in its own <code>Thread</code> and repeatedly tries to write empty strings to the <code>Socket</code> until that raises a <code>SocketClosedException</code>.</p>\n'}, {'answer_id': 147160, 'author': 'Darron', 'author_id': 22704, 'author_profile': 'https://Stackoverflow.com/users/22704', 'pm_score': -1, 'selected': False, 'text': '<p>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.</p>\n'}, {'answer_id': 21961672, 'author': 'user207421', 'author_id': 207421, 'author_profile': 'https://Stackoverflow.com/users/207421', 'pm_score': 0, 'selected': False, 'text': "<p>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.</p>\n"}]
['https://Stackoverflow.com/questions/22720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2362/']