Files
jsmind_xiezuo_project/all_use_write/test/test4.py
T
2024-03-21 20:32:50 +08:00

22 lines
609 B
Python

import asyncio
import websockets
# 存储所有连接的客户端
connected_clients = set()
async def broadcast(message):
if connected_clients:
await asyncio.wait([client.send(message) for client in connected_clients])
async def handler(websocket, path):
connected_clients.add(websocket)
try:
async for message in websocket:
await broadcast(message)
finally:
connected_clients.discard(websocket)
start_server = websockets.serve(handler, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()