我使用以下代码为javascript EventSource
实现后端from flask import Flask, Response
from time import sleep
import time
class ServerSentEvent(object):
def __init__(self, data):
self.data = data
self.event = None
self.id = None
self.desc_map = {
self.data : "data",
self.event : "event",
self.id : "id",
self.retry: 500
}
def encode(self):
if not self.data:
return ""
lines = ["%s: %s" % (v, k)
for k, v in self.desc_map.items() if k]
return "%s\n\n" % "\n".join(lines)
def stream():
while True:
ev = ServerSentEvent('hi ' + str(int(round(time.time()))))
yield ev
sleep(0.1)
app = Flask(__name__)
@app.route("/events")
def streamSessionEvents():
return Response(stream(), mimetype="text/event-stream")
@app.route("/")
def index():
template = """
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
var source = new EventSource('/events')
source.onmessage = function (event) {
$('#log').append(event.data + '</br>')
}
</script>
</head>
<body>
<div id="log"></div>
</body>
</html>
"""
return(template)
app.run(threaded=True)
然而,EventSource每隔3秒(这是默认值)保持重新连接,因为服务器在每次事件后关闭连接。如何建立连续连接?