views:

1237

answers:

3

Hi,

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() Socket method 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

A: 

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.

James A. Rosen
A: 

Hoped there'd be a more elegant way.. oh well

Brabster
A: 

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.

Darron