I created a route /stream
which should push the string 'test' every second.
When I open this URL (localhost:12346/stream
) on Chrome, it indeed opens a blank page and a "test" is appended to the page every second, so I think the server side is working correctly. When I opened it on Firefox, it treats it as a file download that never finishes.
But when I open client.html
below, the onmessage
event of the EventSource object is never fired so I get no data. The onopen
event was fired and I see it in the console. Why is this? How can I receive the data in the JavaScript side?
server.py:
import flask
import flask_cors
import time
app = flask.Flask(__name__)
app.debug = True
flask_cors.CORS(app)
def event_stream():
while True:
time.sleep(1)
yield 'test\n'
@app.route('/stream')
def stream():
return flask.Response(event_stream(), mimetype='text/event-stream')
app.run(port=12346, threaded=True)
client.html:
<!DOCTYPE html>
<html>
<body>
<script>
var source = new EventSource('http://localhost:12346/stream');
source.onopen = e => console.log('opened', event);
source.onerror = e => console.log('error', event);
source.onmessage = e => console.log('onmessage', event);
</script>
</body>
</html>