使用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错误:The connection to http://localhost:8080/gettime was interrupted while the page was loading.
根据spec,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
答案 0 :(得分:1)
答案 1 :(得分:0)
关于这些东西的规范是不断变化的,并且有一些与规范提出的重新连接行为相关的开放规范问题。我不会依赖任何特定的重新连接行为,直到规范比目前为止稳定得多。