import asyncio import websockets class WebsockUtil: def __init__(self): self.clients = set() asyncio.run(self.start()) async def handler(websocket, path): # 将新连接的客户端加入列表 clients.add(websocket) try: async for message in websocket: # 将收到的消息广播给所有客户端 for client in clients: await client.send(message) finally: # 将断开连接的客户端从列表中删除 clients.remove(websocket) async def start(): async with websockets.serve(self.handler, "127.0.0.1", 5001): await asyncio.Future() # 防止 main() 函数结束