Files
live-campus-mcs-p-2027.2/Semaine_09/Socket_chat/server_websocket.py
T
gauvainboiche ce1f0e513a feat: Semaine 9
2026-05-15 16:24:56 +02:00

28 lines
1014 B
Python

# server
import asyncio
import websockets
clients_connectes : set[websockets.ServerConnection] = set()
async def handle_client(websocket: websockets.ServerConnection):
clients_connectes.add(websocket)
print(f"Connexion : {websocket.remote_address}{len(clients_connectes)} client(s) connecté(s)")
try:
async for message in websocket:
print(f"Message de {websocket.remote_address} : {message}")
destinataires = clients_connectes - {websocket}
if destinataires:
await asyncio.gather(
*[client.send(message) for client in destinataires]
)
finally:
clients_connectes.discard(websocket)
print(f"Déconnexion : {websocket.remote_address}{len(clients_connectes)} client(s) restant(s)")
async def main():
async with websockets.serve(handle_client, "localhost", 8765):
print("Serveur de chat sur ws://localhost:8765")
await asyncio.Future()
asyncio.run(main())