Skip to main content
 首页 » 编程设计

python之如何使用 BaseHTTPRequestHandler 知道客户端关闭了连接

2025年05月04日12arxive

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

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

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

请您参考如下方法:

您可以将这些方法添加到您的 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中,您可以添加一些您希望在每次发生套接字错误(例如客户端关闭连接)时执行的代码。