2

我正在编写可以为客户端提供大文件的 http 服务器。

在写入 wfile 流时,客户端可能会关闭连接并且我的服务器会收到套接字错误(Errno 10053)。

客户端关闭连接时是否可以停止写入?

4

1 回答 1

1

您可以将这些方法添加到您的BaseHTTPRequestHandler类中,这样您就可以知道客户端是否关闭了连接:

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

在第二种方法:connection_dropped中,您可以添加一些您希望在每次发生套接字错误(例如客户端关闭连接)时执行的代码。

于 2012-03-29T20:01:59.167 回答