2

I am writing http server that can serve big files to client.

While writing to wfile stream it is possible that client closes connection and my server gets socket error (Errno 10053).

Is it possible to stop writing when client closes connection?

Dmitrii Tokarev
  • 137
  • 3
  • 9

1 Answers1

1

You can add these methods to your BaseHTTPRequestHandler class so that you can know if the client closed the connection:

def handle(self):
    """Handles a request ignoring dropped connections."""
    try:
        return BaseHTTPRequestHandler.handle(self)
    except (socket.error, socket.timeout) as e:
        self.connection_dropped(e)

def connection_dropped(self, error, environ=None):
    """Called if the connection was closed by the client.  By default
    nothing happens.
    """
    # add here the code you want to be executed if a connection
    # was closed by the client

In the second method: connection_dropped, you can add some code that you want to be executed each time a socket error (e.g. client closed the connection) occures.

Thanasis Petsas
  • 4,378
  • 5
  • 31
  • 57
  • socket.error is only thrown when sending data to client (self.wfile.write). Do you know any way to determine whether pipe is broken without trying to send anything? – Dzmitry Lazerka Sep 19 '12 at 03:41
  • Maybe you can catch the `IOError` with the `errno.EPIPE` code. You can find more info here: http://stackoverflow.com/questions/180095/how-to-handle-a-broken-pipe-sigpipe-in-python – Thanasis Petsas Sep 19 '12 at 12:54