Leon Leon - 8 months ago 39
Java Question

How could I know the status of the socket connection inside a PrintWriter

I use

PrintWriter output = new PrintWriter(socket.getOutputStream(), true);


Since the println function doesn't has return value, it don't throw any exception either.
How could I know the disconnection is cut off?



Calling PrintWriter.checkError() will tell you if any error has occurred. It won't specifically tell you which error occurred, but if checkError returns true you can infer that a closed or broken socket was the most likely cause.

If you keep a reference to the socket that you got the input stream from, you can test the status of the socket.

Finally, if you really want to know exactly when and why the stream "failed", you could create a wrapper for OutputStream that caught IOException on the write methods (etc) and rethrew it wrapped in some unchecked exception.