import asyncio import websockets import json connected_clients = set() # ✅ 适配 websockets >=11.x,只接受 websocket 参数 async def ws_handler(websocket): connected_clients.add(websocket) print("客户端已连接") try: async for message in websocket: print("收到前端消息:", message) except websockets.exceptions.ConnectionClosed: print("客户端断开连接") finally: connected_clients.remove(websocket) # 推送消息到所有前端 async def push_to_all_clients(user_data: dict,type: str = "join"): # ✅ 直接发送结构化 JSON message = { "type": type, "data": user_data } for client in connected_clients.copy(): try: await client.send(json.dumps(message)) # ✅ 注意是 JSON 序列化 except: pass # 启动 WebSocket 服务 async def ws_main(): print("✅ WebSocket 服务已启动:ws://127.0.0.1:8888") async with websockets.serve(ws_handler, "0.0.0.0", 8888): await asyncio.Future() # 永远挂起,保持服务运行 # 主线程中调用这个方法推送消息 def push_to_frontend(user_data, type: str = "join"): loop = asyncio.get_event_loop() if loop.is_running(): asyncio.run_coroutine_threadsafe(push_to_all_clients(user_data, type), loop) else: loop.run_until_complete(push_to_all_clients(user_data, type)) # 在线程中启动服务 def start_ws_server(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(ws_main())