socketio的start_background_task函数用于新建一个线程,处理业务,在线程中在请求上下文中调用收发功能函数git
app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app, async_mode=async_mode) 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}, namespace='/test') @socketio.on('connect', namespace='/test') def test_connect(): global thread if thread is None: thread = socketio.start_background_task(target=background_thread) emit('my_response', {'data': 'Connected', 'count': 0})
来自flask-socketio官方github示例代码github
https://github.com/miguelgrinberg/Flask-SocketIO/blob/master/example/app.pyflask
包括了基本的函数调用状况,极具实用价值app