tags:

views:

2163

answers:

3

For some of my Java NIO connections, when I have a SocketChannel.write(ByteBuffer) call, it throws an IOException: "Broken pipe".

What causes a "broken pipe", and more importantly, is it possible to recover from that state? If it cannot be recovered, it seems this would be a good sign that an irreversible problem has occurred and that I should simply close this socket connection. Is that a reasonable assumption? Is there ever a time when this IOException would occur while the socket connection is still being properly connected in the first place (rather than a working connection that failed at some point)?

On a side note, is it wise to always call SocketChannel.isConnected() before attempting a SocketChannel.write(), and if so, can I also assume that the connection is "broken" and should be closed if both SocketChannel.isConnected() and SocketChannel.isConnectionPending() are both false?

Thanks!

+2  A: 

Broken pipe simply means that the connection has failed. It is reasonable to assume that this is unrecoverable, and to then perform any required cleanup actions (closing connections, etc). I don't believe that you would ever see this simply due to the connection not yet being complete.

If you are using non-blocking mode then the SocketChannel.connect method will return false, and you will need to use the isConnectionPending and finishConnect methods to insure that the connection is complete. I would generally code based upon the expectation that things will work, and then catch exceptions to detect failure, rather than relying on frequent calls to "isConnected".

jsight
+2  A: 

You should assume the socket was closed on the other end. Wrap your code with a try catch block for IOException.

You can use isConnected() to determine if the SocketChannel is connected or not, but that might change before your write() invocation finishes. Try calling it in your catch block to see if in fact this is why you are getting the IOException.

Sean A.O. Harney
+2  A: 

It is not a good idea to call isConnected() before write() because there is a small chance that the socket will be closed between the two calls. It is a better idea to catch the IOException resulting from the failed write() and take whatever remedial action is required.

Stephen C