update tryhard websockets

This commit is contained in:
edbernar
2024-07-31 16:55:50 +02:00
parent 2e31a335e3
commit 8989e71c1a
2 changed files with 17 additions and 12 deletions

View File

@ -4,7 +4,11 @@ import websockets
async def send_messages(websocket):
while True:
message = input("Enter message to send: ")
if (websocket.open):
await websocket.send(message)
else:
print("Connection closed")
break
print(f"Sent: {message}")
async def receive_messages(websocket):
@ -19,5 +23,4 @@ async def main():
receive_task = asyncio.create_task(receive_messages(websocket))
await asyncio.gather(send_task, receive_task)
# Démarrer le client
asyncio.run(main())

View File

@ -8,21 +8,23 @@ async def handler(websocket, path):
connected_clients.add(websocket)
try:
async for message in websocket:
for client in connected_clients:
if client == websocket:
print(f"Message reçu: {message}")
if message == validTokens:
await client.send("Token valide")
else:
await client.send("Token invalide")
if client != websocket:
await client.send(message)
print(f"Received {message}")
# for client in connected_clients:
# if client == websocket:
# print(f"Received {message}")
# await websocket.close()
# if client != websocket:
# await client.send(message)
except websockets.exceptions.ConnectionClosed as e:
print(f"Connexion fermée: {e}")
finally:
print("Client déconnecté")
connected_clients.remove(websocket)
start_server = websockets.serve(handler, "localhost", 8000)
try:
start_server = websockets.serve(handler, "localhost", 8000, reuse_address=True)
except OSError as e:
print(f"Error: {e}")
exit(1)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()