How to Solve Python socket:[Errno 32] Broken pipe

This error occurs when the client side closes its current socket connection to your server side, but your server side is busy sending data to a socket that is already disconnected.

Here is the solution given by stackoverflow:

Your server process has received a SIGPIPE writing to a socket. This usually happens when you write to a socket fully closed on the other (client) side. This might be happening when a client program doesn’t wait till all the data from the server is received and simply closes a socket (using close function). In a C program you would normally try setting to ignore SIGPIPE signal or setting a dummy signal handler for it. In this case a simple error will be returned when writing to a closed socket. In your case a python seems to throw an exception that can be handled as a premature disconnect of the client.

Here is the python implementation:

import socket
def hack_fileobject_close():
    if getattr(socket._fileobject.close, '__hacked__', None):
        return
    old_close = socket._fileobject.close
    def new_close(self, *p, **kw):
        try:
            return old_close(self, *p, **kw)                                                                                                                                    
        except Exception, e:
            print("Ignore %s." % str(e))
    new_close.__hacked__ = True
    socket._fileobject.close = new_close
hack_fileobject_close()

Similar Posts: