下面已经用node.js给出了答案。
How to close a "Server-Sent Events"-connection on the server?
但是,如何在 python Flask 中做同样的事情呢?
最佳答案
重要的是要注意您还需要关闭客户端上的连接,否则它会在 retry
超时后尝试重新打开连接。
这让我很困惑,直到我在这里看到这篇文章:https://stackoverflow.com/a/38235218/5180047
来自链接:
The problem here is that the server unexpectedly closes the connection, instead of doing its work while leaving it open. When this happnes, the client re-sends a request to open a connection and to start streaming Server Sent Events. The server then closes the connection again and again, leading to an infinite loop.
在我看到这个之后..我的首选解决方案是通过产生预期的数据消息来关闭与服务器的连接。
在客户端(浏览器)
var sse = new EventSource('/sse');
sse.addEventListener('message', function(e) {
console.log(e);
var data = e.data;
if (!data) {
console.log('no data in event');
return;
}
if (data === 'finished') {
console.log('closing connection')
sse.close()
}
// my work here based on message
});
我的 Flask 服务器
from flask import Response
@app_api.route("/sse")
def stream():
def trackerStream():
finished = check_if_finished()
while not finished:
sleep(1) # poll timeout
if should_send_event():
yield f"data: {mydata()}\n\n"
else:
yield "data: nodata\n\n"
finished = check_if_finished()
yield "data: finished\n\n"
return Response(trackerStream(), mimetype="text/event-stream")
注意:确保您总是在某个时间间隔内从服务器向客户端发送事件。如果用户关闭浏览器,flask 将在尝试写入套接字时出错并为您关闭流。如果您不定期向客户端写入数据,即使您只是写入 data: nodata\n\n
,服务器也可能陷入循环。
关于python - 如何关闭 Flask 中的服务器发送事件连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11597367/