在一对多的WebSocket场景下,如果你想要向特定的多个客户端发送消息,而不是广播给所有客户端,你需要维护一个能够标识每个客户端的方式,比如使用用户名或者客户端ID。这样,你就可以根据需要选择向哪些客户端发送消息。
import asyncio
import websockets
# 使用字典存储每个客户端的连接,键为客户端ID
connected_clients = {}
async def send_to_clients(client_ids, message):
"""向指定的客户端ID列表发送消息"""
tasks = []
for client_id in client_ids:
if client_id in connected_clients:
tasks.append(connected_clients[client_id].send(message))
if tasks:
await asyncio.wait(tasks)
async def handler(websocket, path):
"""处理单个客户端的连接"""
# 假设客户端在连接时发送其ID作为第一条消息
client_id = await websocket.recv()
print(f"New client connected with ID: {client_id}")
# 将客户端ID与连接关联起来
connected_clients[client_id] = websocket
try:
async for message in websocket:
print(f"Received from {client_id}: {message}")
# 这里可以添加逻辑判断是否需要向特定客户端发送消息
# 例如,向ID为'client2'和'client3'的客户端发送消息
await send_to_clients(['client2', 'client3'], f"Forwarded to you from {client_id}: {message}")
finally:
# 当客户端断开连接时,从字典中移除
if client_id in connected_clients:
del connected_clients[client_id]
# 开始WebSocket服务器
start_server = websockets.serve(handler, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()