Flask SocketIO 服务端向客户端实时推送
先撸码,后废话!App.py Code:#!/usr/bin/env python# -*- coding: utf-8 -*-from flask import Flask, render_templatefrom flask_socketio import SocketIOfrom threading import Lockimport randomasync_mode = Noneapp =
·
先撸码,后废话!
App.py Code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask, render_template
from flask_socketio import SocketIO
from threading import Lock
import random
async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)
thread = None
thread_lock = Lock()
@app.route('/')
def index():
return render_template('index.html', async_mode=socketio.async_mode)
@socketio.on('connect', namespace='/test_conn')
def test_connect():
global thread
with thread_lock:
if thread is None:
thread = socketio.start_background_task(target=background_thread)
def background_thread():
while True:
socketio.sleep(2)
t = random.randint(1, 100)
socketio.emit('server_response', {'data': t}, namespace='/test_conn')
@socketio.on('disconnect', namespace='/chat')
def test_disconnect():
print('Client disconnected')
if __name__ == '__main__':
socketio.run(app, debug=True)
Index.html Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="//cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script type="text/javascript" src="//cdn.bootcdn.net/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
</head>
<body>
<h1 id="tag"></h1>
<script type="text/javascript">
$(document).ready(function() {
namespace = '/test_conn';
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port + namespace);
socket.on('server_response', function(res) {
console.log(res.data);
$('#tag').text(res.data);
});
});
</script>
</body>
</html>
Browser Effects:
后记:
代码实现的基本效果是后端2秒生成一次随机数,将生成后的结果推送到前端。
同样的效果用 Ajax 轮询也是可以做到的,Ajax轮询原理是设置定时器,定时通过AJAX同步服务端数据。但是这种方式存在延时且对服务端造成较大的负载。
而使用 SocketIO 只需要客户端连接一次,然后维护一个永久的TCP连接,数据更实时。
SocketIO(服务端有消息立刻推送):小弟,有人给你发了条消息,你收一下
Ajax(定时查询服务端是否有消息):老头,有消息吗?有消息的话你给我
参考文章:
Flask-SocketIO笔记
官方示例文档(超干货)
更多推荐
所有评论(0)