用 Python 和 CherryPy 实现的测试用例:
import cherrypy, time
class Root():
@cherrypy.expose
def index(self):
return r'''<!DOCTYPE html>
<html>
<head>
<title>Server-sent events test</title>
<style>html,body,#test{height:98%;}</style>
</head>
<body>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
var source = new EventSource('gettime');
source.addEventListener('time', function (event) {
document.getElementById('test').innerHTML += event.data + "\n";
});
source.addEventListener('error', function (event){
console.log('SSE error:', event);
console.log('SSE state:', source.readyState);
});
}, false);
</script>
<textarea id="test"></textarea>
</body>
</html>'''
@cherrypy.expose
def gettime(self):
cherrypy.response.headers["Content-Type"] = "text/event-stream"
def generator():
while True:
time.sleep(1)
yield "event: time\n" + "data: " + str(time.time()) + "\n\n"
return generator()
gettime._cp_config = {'response.stream': True}
if __name__ == '__main__':
cherrypy.config.update({'server.socket_host': '0.0.0.0'})
cherrypy.quickstart(Root())
成功接收到一些消息后,我手动断开连接,然后在 Firefox 的 Web 控制台中出现 JS 错误:在加载页面时与 http://localhost:8080/gettime 的连接被中断。
根据spec , 如果连接关闭,客户端将重新连接
,但 Firefox 不会。错误事件处理程序报告 source
处于 CLOSED
状态。
关闭(数值 2)
连接未打开,用户代理未尝试重新连接。要么出现 fatal error ,要么调用了 close() 方法。
所以出现了 fatal error ?
- 在 Chromium 中它可以工作,错误处理程序报告
source
处于CONNECTING
(0) 状态(应该如此)并且连接会在几秒钟内自动恢复 - 在 Linux 和 Windows 平台上尝试过 Firefox 26、Firefox 24 ESR 和 Iceweasel 17,都一样
- 已检查原始协议(protocol)和 header ,看起来没问题
- 已尝试为每个发送的事件添加
retry: 3000
- 尝试将 JavaScript 移出事件监听器并将其包装到 setTimeout 中
最佳答案
The bug已在 Firefox 36 中修复。
关于python - Firefox 不恢复服务器发送的事件连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20837460/