python - Firefox 不恢复服务器发送的事件连接

标签 python html firefox cherrypy server-sent-events

用 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/

相关文章:

python - 如何对同一个字典值同时使用键和索引?

python - 无法通过 Gather 方法 twilio 中的 action prop 重定向到方法 url

javascript - 如何实现Google饼图(带有图例显示和相应的值)

python - 使用 BeautifulSoup 修改 HTML

javascript - 可以停止复制+粘贴到 html 文本框中吗?

javascript - Python 中的浏览器 'window' 对象等效吗?

firefox - CSS 框阴影问题

CSS - 字体在 Firefox 和 Chrome 中呈现不同

javascript - Safari 为 Date toISOString() 返回不正确的值

python - python 中此表达式的代码