update tryhard websockets

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

View File

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

View File

@ -8,21 +8,23 @@ async def handler(websocket, path):
connected_clients.add(websocket) connected_clients.add(websocket)
try: try:
async for message in websocket: async for message in websocket:
for client in connected_clients: print(f"Received {message}")
if client == websocket: # for client in connected_clients:
print(f"Message reçu: {message}") # if client == websocket:
if message == validTokens: # print(f"Received {message}")
await client.send("Token valide") # await websocket.close()
else: # if client != websocket:
await client.send("Token invalide") # await client.send(message)
if client != websocket:
await client.send(message)
except websockets.exceptions.ConnectionClosed as e: except websockets.exceptions.ConnectionClosed as e:
print(f"Connexion fermée: {e}") print(f"Connexion fermée: {e}")
finally: finally:
print("Client déconnecté") print("Client déconnecté")
connected_clients.remove(websocket) 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_until_complete(start_server)
asyncio.get_event_loop().run_forever() asyncio.get_event_loop().run_forever()