问题描述
每次当我从客户端刷新页面时,都会与 Flask 服务器建立一个新连接,它运行函数“backgroundFunction()”而不退出最近打开的函数,并且随着我一次又一次地刷新页面,数字会增加.
from flask import Flask
from flask_socketio import SocketIO,send,emit
import socket
from time import sleep
import datetime
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['DEBUG'] = True
socketio = SocketIO(app,cors_allowed_origins="*",async_mode = None,logger = False,engineio_logger = False)
def backgroundFunction():
while True:
data = "I am Data"
socketio.emit('data',data,broadcast=True)
socketio.sleep(2)
@socketio.on('connect')
def socketcon():
print('Client connected')
socketio.start_background_task(backgroundFunction)
if __name__ == ("__main__"):
socketio.run(app,port=5009)
解决方法
查看 Flask-SocketIO 存储库中的示例代码,了解实现在第一次触发事件时启动的后台作业的一种可能方法。
代码是 here。以下是相关摘录:
thread = None
thread_lock = Lock()
def background_thread():
"""Example of how to send server generated events to clients."""
count = 0
while True:
socketio.sleep(10)
count += 1
socketio.emit('my_response',{'data': 'Server generated event','count': count})
@socketio.event
def connect():
global thread
with thread_lock:
if thread is None:
thread = socketio.start_background_task(background_thread)