如何用烧瓶实现SSE

时间:2019-10-30 02:47:43

标签: javascript python flask

我尝试了带烧瓶的SSE,没有带烧瓶的SSE。 服务器端的代码如下。

# run.py
from sse_test import app
app.run(debug=True, port=5002)
# sse_test/__init__.py
from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

import sse_test.views
# sse_test/views.py
from sse_test import app

from flask import Response
import time

@app.route('/stream')
def stream():
    def sse_response():
        while True:
            yield str(time.time()) + '\n'
            time.sleep(2)
            print('streamed')
    res =  Response(sse_response(), mimetype='text/event-stream')
    return res

然后是客户端的代码。

<!doctype html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>SSE Test</title>
  </head>
  <body>
    <script src="script.js"></script>
  </body>
</html>
window.onload = function () {
  const eventSource = new EventSource("http://localhost:5002/stream");

  eventSource.onopen = function (e) {
    console.log('opend');
  }

  eventSource.onmessage = function (e) {
    console.log(e.data);
  }

  eventSource.onerror = function (e) {
    console.log('errored');
  }
}

我在浏览器的控制台中“打开”,并在服务器的控制台中“流式传输”,但是在浏览器的控制台中无法获得响应消息。 但是,我直接使用Chrome浏览了“ http://localhost:5002”,Chrome在页面中显示了响应消息。

我的代码哪里出问题了?

谢谢。

0 个答案:

没有答案