目标:
socketio.run(app) 启动服务器并使用 while 循环将数据无限地发送到多个 JavaScript(客户端)。
数据来自另一个 while 循环,但该循环需要在脚本运行后启动(独立于客户端连接)以供其他使用。
当前的:
对于第一点,我已经有以下代码:
def background_thread():
while True:
socketio.emit('response',{'data': value},namespace='/test')
@socketio.on('connect', namespace='/test')
def test_connect():
global thread
with thread_lock:
if thread is None:
thread = socketio.start_background_task(target=background_thread)
emit('response', {'data': 'Connected'})
if __name__ == '__main__':
socketio.run(app, debug=True, host='localhost', port=args.portNum)
Run Code Online (Sandbox Code Playgroud)从上面,我仅在客户端连接到服务器后添加一个线程。我不知道如何从这一点实现第2点?我正在考虑使用另一个线程,但在组织代码时遇到问题,以便在客户端连接到服务器后socketio.start_background_task可以与默认 python 线程无限共享数据。
附加问题:如何让多个客户端连接到一台服务器?
谢谢大家!