feat: Semaine 9
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
# 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())
|
||||
Reference in New Issue
Block a user