用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的网络控制台出现JS错误。The connection to http://localhost:8080/gettime was interrupted while the page was loading.
根据... 规范, Clients will reconnect if the connection is closed
但Firefox没有。错误事件处理程序报告说 source
是在 CLOSED
状态。
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.
所以出现了一个致命的错误?
source
是在 CONNECTING
(0)状态(如其所愿),并在几秒钟内自动恢复连接。retry: 3000
到每个发送事件漏洞 在Firefox 36中得到了修复。
关于这个东西的规范是在不断变化的,有一些开放的规范问题与规范提出的重连接行为有关。 在规范比目前稳定很多之前,我不会依赖任何具体的重连接行为。