工程原因需要后端实时推送数据到前端,并在前端进行相应的显示响应
项目架构
static存放css、js、images等静态数据
templates存放html网页文件
实现
后端main.py
from flask_socketio import SocketIO
from flask import Flask, render_template, request
from threading import Lock
thread = None
thread_lock = Lock()
app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins='*')
connected_sids = set() # 存放已连接的客户端
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('connect')
def on_connect():
connected_sids.add(request.sid)
print(f'{request.sid} 已连接')
global thread
with thread_lock:
print(thread)
if thread is None:
# 如果socket连接,则开启一个线程,专门给前端发送消息
thread &