Flask服务器发送事件套接字异常

Nin*_*zAI 5 javascript python flask server-sent-events

我正在考虑使用SSE将新数据推送到客户端并使用Flot(javascript图表库)显示"实时"更新.我的服务器在python Flask框架上运行,我已经想出如何将数据推送到客户端,但是一旦我离开页面就会出现问题:

Exception happened during processing of request from ('127.0.0.1', 38814)
Traceback (most recent call last):
  File "/usr/lib/python2.7/SocketServer.py", line 582, in process_request_thread
    self.finish_request(request, client_address)
  File "/usr/lib/python2.7/SocketServer.py", line 323, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python2.7/SocketServer.py", line 640, in __init__
    self.finish()
  File "/usr/lib/python2.7/SocketServer.py", line 693, in finish
    self.wfile.flush()
  File "/usr/lib/python2.7/socket.py", line 303, in flush
    self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
Run Code Online (Sandbox Code Playgroud)

我理解为什么会发生错误 - 由于无限循环提供"实时"数据,套接字永远不会关闭.问题是我如何检测页面更改并干净地关闭套接字?我可以在客户端关闭连接吗?如何检测页面更改呢?

这是服务器代码框架,我当然会用包含要显示的对象列表的json替换文本消息:

def event_stream():
    import time
    while True:
        time.sleep(1)
        yield "data: This is a message number X.\n\n"

@app.route('/stream')
def stream():
    return Response(event_stream(), mimetype="text/event-stream")
Run Code Online (Sandbox Code Playgroud)

bbe*_*e10 2

您可以使用onBeforeUnload或 jQuerywindow.unload()对某些关闭句柄的拆卸方法进行 Ajax 调用。就像是:

$(window).unload(
    function() {
        $.ajax(type: 'POST',
               async: false,
               url: 'foo.com/client_teardown')
    }
}
Run Code Online (Sandbox Code Playgroud)

unload()/的处理方式存在一些不一致onBeforeUnload(),因此您可能在 Chrome 之类的工具中需要做更多工作。