The most common reason I've had for a "broken pipe" is that one machine (of a pair communicating via socket) has shut down its end of the socket before communication was complete. About half of those were because the program communicating on that socket had terminated.
If the program sending bytes sends them out and immediately shuts down the socket or terminates itself, it is possible for the socket to cease functioning before the bytes have been transmitted and read.
Try putting pauses anywhere you are shutting down the socket and before you allow the program to terminate to see if that helps.
FYI: "pipe" and "socket" are terms that get used interchangeably sometimes.