如何关闭并重启Python WebSocket线程?技术实现问题求助
如何正确停止并重启WebSocket线程?
我尝试关闭并重启一个WebSocket线程但未能成功,核心问题在于wsl_thread()函数中的wsl.run_forever()会持续阻塞,无法回到循环中检查to_restart_wsl[pair]标志,导致线程无法停止。threading模块没有直接杀死线程的方法,Thread.join()会一直等待线程结束,但线程因run_forever()持续运行永远不会结束。
原代码
import threading import websocket import time # 原代码遗漏time模块,此处补充 pair = 'XRPMYR' # 初始化重启标志字典 to_restart_wsl = {} to_restart_wsl[pair] = False def wsl_open(ws, pair): # 示例on_open实现,可按需修改 print(f"{pair} WebSocket连接已打开") def wsl_message(ws, msg, pair): # 示例on_message实现,可按需修改 print(f"{pair} 收到消息: {msg}") def wsl_thread(pair): wsl_url = f"wss://ws.luno.com/api/1/stream/{pair}" while not to_restart_wsl[pair]: try: wsl = websocket.WebSocketApp(wsl_url, on_open=lambda ws: wsl_open(ws, pair), on_message=lambda ws, msg: wsl_message(ws, msg, pair)) print(f"{pair} Luno websocket feed started.") wsl.run_forever() except Exception as e: print(e) time.sleep(5) # 创建并启动线程 luno_thread = threading.Thread(target=wsl_thread, args=(pair,), name=pair) luno_thread.start() # 尝试停止线程(无效) to_restart_wsl[pair] = True luno_thread.join() # 尝试重启线程(无效) to_restart_wsl[pair] = False luno_thread = threading.Thread(target=wsl_thread, args=(pair,)) luno_thread.start()
曾尝试的无效方法
我曾尝试新建一个WebSocket实例调用close()来关闭连接,但这只会关闭新创建的实例,无法终止原线程中的连接:
def close_wsl(pair): wsl_url = f"wss://ws.luno.com/api/1/stream/{pair}" try: wsl = websocket.WebSocketApp(wsl_url) wsl.close() print(f"{pair} websocket feed closed, it should auto restart.") except Exception as e: print(e) to_restart_wsl[pair] = True close_wsl(pair) luno_thread.join() to_restart_wsl[pair] = False luno_thread = threading.Thread(target=wsl_thread, args=(pair,)) luno_thread.start()
解决方案
要解决这个问题,需要保存线程中正在运行的WebSocket实例,在需要停止时主动调用它的close()方法,让run_forever()退出阻塞,回到循环中检查重启标志。
修改后的代码如下:
import threading import websocket import time pair = 'XRPMYR' to_restart_wsl = {} to_restart_wsl[pair] = False # 用字典保存每个交易对对应的WebSocket实例 active_ws = {} def wsl_open(ws, pair): print(f"{pair} WebSocket连接已打开") def wsl_message(ws, msg, pair): print(f"{pair} 收到消息: {msg}") def wsl_thread(pair): wsl_url = f"wss://ws.luno.com/api/1/stream/{pair}" while not to_restart_wsl[pair]: try: wsl = websocket.WebSocketApp(wsl_url, on_open=lambda ws: wsl_open(ws, pair), on_message=lambda ws, msg: wsl_message(ws, msg, pair)) # 将当前WebSocket实例存入字典 active_ws[pair] = wsl print(f"{pair} Luno websocket feed started.") wsl.run_forever() except Exception as e: print(e) # 退出run_forever后,移除实例 if pair in active_ws: del active_ws[pair] time.sleep(5) # 创建并启动线程 luno_thread = threading.Thread(target=wsl_thread, args=(pair,), name=pair) luno_thread.start() # 正确停止线程的步骤 to_restart_wsl[pair] = True # 调用当前WebSocket实例的close()方法,终止run_forever() if pair in active_ws: active_ws[pair].close() # 等待线程结束 luno_thread.join() # 重启线程 to_restart_wsl[pair] = False luno_thread = threading.Thread(target=wsl_thread, args=(pair,)) luno_thread.start()
关键说明
- 新增
active_ws字典保存每个交易对对应的WebSocket实例,确保能操作到线程中正在运行的连接。 - 停止线程时,先设置
to_restart_wsl[pair] = True,再调用active_ws[pair].close(),让run_forever()立即退出阻塞。 - 线程退出
run_forever()后,会回到循环检查to_restart_wsl[pair],此时标志为True,循环结束,线程正常退出。 - 最后重新创建并启动线程即可完成重启。
内容的提问来源于stack exchange,提问作者wil
相关产品推荐
相关产品推荐

