首页 > 解决方案 > 建立新连接时如何退出从 socketio.start_background_task() 创建的先前打开的函数

问题描述

每次我从客户端刷新页面时,都会与烧瓶服务器建立新连接,它会运行函数“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)

标签: pythonflasksocket.ioflask-socketio

解决方案


查看 Flask-SocketIO 存储库中的示例代码,了解一种可能的方式来实现在第一次触发事件时启动的后台作业。

代码在这里。以下是相关摘录:

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)

推荐阅读