在流响应(服务器发送事件)Flask中检测客户端断开连接

时间:2016-02-11 00:26:09

标签: python sockets flask server server-sent-events

我正在使用SSE编写Flask服务器并遇到与Flask server sent events socket exception相同的问题。寻找更好的答案,因为例如浏览器没有正常退出,让客户负责是不好的。

在上述问题的代码上下文中,Flask服务器使用响应mimetype="text/event-stream"将事件发送到客户端,响应对象只是一个连续生成数据的协同例程。如果客户端在不调用close()的情况下断开连接,则服务器将获得异常Errno 32 Broken Pipe

在return语句周围放置一个try会捕获一个错误,但它不会阻止打印下面的日志:

Traceback (most recent call last):
  File "/Users/miluo/development/build/venv/lib/python2.6/site-packages/gevent/pywsgi.py", line 508, in handle_one_response
    self.run_application()
  File "/Users/miluo/development/build/venv/lib/python2.6/site-packages/gevent/pywsgi.py", line 495, in run_application
    self.process_result()
  File "/Users/miluo/development/build/venv/lib/python2.6/site-packages/gevent/pywsgi.py", line 486, in process_result
    self.write(data)
  File "/Users/miluo/development/build/venv/lib/python2.6/site-packages/gevent/pywsgi.py", line 376, in write
    self._write(data)
  File "/Users/miluo/development/build/venv/lib/python2.6/site-packages/gevent/pywsgi.py", line 369, in _write
    self._sendall(data)
  File "/Users/miluo/development/build/venv/lib/python2.6/site-packages/gevent/pywsgi.py", line 355, in _sendall
    self.socket.sendall(data)
  File "/Users/miluo/development/build/venv/lib/python2.6/site-packages/gevent/socket.py", line 460, in sendall
    data_sent += self.send(_get_memory(data, data_sent), flags)
  File "/Users/miluo/development/build/venv/lib/python2.6/site-packages/gevent/socket.py", line 437, in send
    return sock.send(data, flags)
error: [Errno 32] Broken pipe
{'GATEWAY_INTERFACE': 'CGI/1.1',
 'HTTP_ACCEPT': 'text/event-stream',
 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, sdch',
 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8',
 'HTTP_CACHE_CONTROL': 'no-cache',
 'HTTP_CONNECTION': 'keep-alive',
 'HTTP_HOST': '0.0.0.0:1234',
 'HTTP_ORIGIN': 'localhost:1122',
 'HTTP_REFERER': 'localhost:1122/',
 'HTTP_USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.103 Safari/537.36',
 'PATH_INFO': '/1',
 'QUERY_STRING': '',
 'REMOTE_ADDR': '127.0.0.1',
 'REMOTE_PORT': '51323',
 'REQUEST_METHOD': 'GET',
 'SCRIPT_NAME': '',
 'SERVER_NAME': 'localhost',
 'SERVER_PORT': '1234',
 'SERVER_PROTOCOL': 'HTTP/1.1',
 'SERVER_SOFTWARE': 'gevent/1.0 Python/2.6',
 'werkzeug.request': None,
 'wsgi.errors': <open file '<stderr>', mode 'w' at 0x105c991e0>,
 'wsgi.input': <gevent.pywsgi.Input object at 0x10753a5d0>,
 'wsgi.multiprocess': False,
 'wsgi.multithread': False,
 'wsgi.run_once': False,
 'wsgi.url_scheme': 'http',
 'wsgi.version': (1, 0)} failed with error

0 个答案:

没有答案