【问题标题】:How to know using BaseHTTPRequestHandler that client closed connection如何使用 BaseHTTPRequestHandler 知道客户端关闭了连接
【发布时间】:2012-04-13 12:15:01
【问题描述】:

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

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

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

【问题讨论】:

    标签: python httpserver basehttprequesthandler


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

    【讨论】:

    • 很高兴我能帮上忙!欢迎来到 Stackoverflow!! :)
    • socket.error 仅在向客户端发送数据时抛出(self.wfile.write)。您是否知道在不尝试发送任何内容的情况下确定管道是否损坏的方法?
    • 也许您可以使用errno.EPIPE 代码捕获IOError。你可以在这里找到更多信息:stackoverflow.com/questions/180095/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    相关资源
    最近更新 更多