问题
Test case implemented with Python and 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())
After receiving some messages successfully I manually drop the connection, then in Firefox' web console appears JS Error: The connection to http://localhost:8080/gettime was interrupted while the page was loading.
According to the spec, Clients will reconnect if the connection is closed
, but Firefox doesn't. Error event handler reports that the source
is in CLOSED
state.
CLOSED (numeric value 2)
The connection is not open, and the user agent is not trying to reconnect. Either there was a fatal error or the close() method was invoked.
So there was a fatal error?
- In Chromium it works, error handler reports that the
source
is inCONNECTING
(0) state (as it should) and connection is automatically restored within a few seconds - Have tried Firefox 26, Firefox 24 ESR and Iceweasel 17 on Linux and Windows platforms, all the same
- Have checked raw protocol and headers, looks ok
- Have tried to add
retry: 3000
to each sent event - Have tried to move JavaScript out of event listener and wrapping it into setTimeout
回答1:
The bug is fixed in Firefox 36.
回答2:
The spec on this stuff is in flux and there is a number of open spec issues related to the reconnection behavior that the spec proposes. I wouldn't rely on any specific reconnection behavior until the spec stabilizes a lot more than it has so far.
来源:https://stackoverflow.com/questions/20837460/firefox-doesnt-restore-server-sent-events-connection