服務(wù)器主動(dòng)推送消息
server.py
import time
from flask import Flask, render_template, jsonify
from flask_sse import sse
from flask_cors import CORS
app = Flask(__name__)
app.config["REDIS_URL"] = "redis://localhost"
app.register_blueprint(sse, url_prefix="/stream")
CORS(app, resources={r"/stream/*": {"origins": "*"}})
@app.route('/')
def index():
return render_template("index.html")
@app.route('/test')
def test():
i=0
while i < 22:
sse.publish({"message": {"name": "dzg", "age": i}}, type="sseTest")
time.sleep(0.31)
i+=1
return jsonify({"code":200})
@app.route('/test1')
def test1():
i=0
while i < 22:
sse.publish({"message": {"name": "dzg", "age": i*i}}, type="sseTest1")
time.sleep(0.31)
i+=1
return jsonify({"code":200})
if __name__ == '__main__':
app.run(host="0.0.0.0")
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>flask-sse test</title>
</head>
<body>
<h1>progress:<span id="a"></span></h1>
<h1>progress:<span id="b"></span></h1>
</body>
<script>
// 創(chuàng)建 EventSource 對(duì)象連接服務(wù)器
var source = new EventSource("/stream")
console.log(source)
// 服務(wù)器發(fā)送信息到客戶端時(shí)硝皂,會(huì)觸發(fā)
source.addEventListener('sseTest', function(event){
var res_data = JSON.parse(event.data);
console.log(res_data);
h = document.getElementById('b')
h.innerText= res_data.message.age
}, false);
source.addEventListener('sseTest1', function(event){
var res_data = JSON.parse(event.data);
console.log(res_data);
h = document.getElementById('a')
h.innerText= res_data.message.age
}, false);
// 連接異常時(shí)會(huì)觸發(fā) error 事件并自動(dòng)重連
source.addEventListener('error', function(event) {
if (event.target.readyState === EventSource.CLOSED) {
console.log('Disconnected');
} else if (event.target.readyState === EventSource.CONNECTING) {
console.log('Connecting...');
}
}, false);
</script>