Search code examples
javasocketsexceptiontcpnio

Broken pipe on TCP socket read


I have an application in Java that opens a TCP server socket and then reads and writes from this socket. I'm running into a problem where the server is getting a IOException with the message "Broken pipe" on a read. I have a good understanding of why this would happen on a write, but I can't figure out why it would happen on a read. For reference, this is the top part of the stack trace

Caused by: java.io.IOException: Broken pipe
at sun.nio.ch.FileDispatcher.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:21)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:198)
at sun.nio.ch.IOUtil.read(IOUtil.java:166)
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:243)

I'm assuming what must be happening is that the OS giving an EPIPE error, but I can't find the code where that would happen. I've looked through the JDK source code (Java and C source) for the text 'Broken pipe' and I can't find the piece of code that is actually generating this exception.

Ultimately the question I'm trying to answer is why this is happening, but I would also accept an answer that simply explains where this error is even generated.


Solution

  • It happens on a read for the same reason it happens on a write. You wrote to a connection that had already been closed by the peer. You got it on the read because the exception was deferred due to buffering.