Files
WLT\Eric.hu 8d1c1cdc7d 'ss'
2025-04-14 15:19:39 +08:00

40 lines
1.3 KiB
Python

import asyncio
import websockets
connected_clients = set()
async def ws_handler(websocket, path=None):
"""处理WebSocket连接"""
print("前端已连接")
connected_clients.add(websocket)
try:
async for message in websocket:
print(f"收到前端消息: {message}")
await broadcast_message(f"回送消息:{message}") # 发送回客户端的消息
except websockets.exceptions.ConnectionClosed as e:
print(f"连接关闭: {e}")
finally:
connected_clients.remove(websocket)
print("客户端断开连接")
async def broadcast_message(msg):
"""广播消息给所有连接的客户端"""
if connected_clients:
# 遍历所有连接的客户端并发送消息
await asyncio.gather(*[client.send(msg) for client in connected_clients]) # 使用 client.open 检查连接状态
else:
print("没有连接的客户端,无法广播消息")
async def start_ws_server():
"""启动WebSocket服务器"""
server = await websockets.serve(ws_handler, '127.0.0.1', 8888)
print("WebSocket 服务器已启动 ws://127.0.0.1:8888")
try:
await server.wait_closed()
except asyncio.CancelledError:
print("服务器已被取消")
if __name__ == '__main__':
asyncio.run(start_ws_server())