赞
踩
服务器推送事件: Server-Sent Events, SSE
使用官方例子
服务端 sse.py
from flask import Flask, render_template
from flask_sse import sse
app = Flask(__name__)
app.config["REDIS_URL"] = "redis://localhost"
app.register_blueprint(sse, url_prefix='/stream')
@app.route('/')
def index():
return render_template("index.html")
@app.route('/hello')
def publish_hello():
sse.publish({"message": "Hello!"}, type='greeting')
return "Message sent!"
客户端
templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Flask-SSE Quickstart</title>
</head>
<body>
<h1>Flask-SSE Quickstart</h1>
<script>
var source = new EventSource("{{ url_for('sse.stream') }}");
source.addEventListener('greeting', function(event) {
var data = JSON.parse(event.data);
console.log("The server says " + data.message);
}, false);
source.addEventListener('error', function(event) {
console.log("Failed to connect to event stream. Is Redis running?");
}, false);
</script>
</body>
</html>
gunicorn sse:app --worker-class gevent --bind 127.0.0.1:8000
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。