我正在考虑使用 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
我理解为什么会发生错误 - 由于无限循环提供“实时”数据,因此套接字永远不会关闭。问题是如何检测页面更改并干净地关闭套接字?我可以关闭客户端的连接吗?那么如何检测页面更改?
这是服务器代码框架,我当然会用包含要显示的对象列表的 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")