我正在编写可以向客户端提供大文件的http服务器。
写入wfile流时,客户端可能会关闭连接,而我的服务器可能会出现套接字错误(Errno 10053)。
当客户端关闭连接时是否可以停止写入?
答案 0 :(得分: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 ,每次发生套接字错误(例如客户端关闭连接)时,您都可以添加一些要执行的代码。