Moving forward on websockets

This commit is contained in:
Kum1ta
2024-07-31 23:41:11 +02:00
parent 08e50356b1
commit e3654d77b6
5 changed files with 70 additions and 41 deletions

View File

@ -1,26 +0,0 @@
import asyncio
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):
while True:
response = await websocket.recv()
print(f"Received: {response}")
async def main():
uri = "ws://localhost:8000"
async with websockets.connect(uri) as websocket:
send_task = asyncio.create_task(send_messages(websocket))
receive_task = asyncio.create_task(receive_messages(websocket))
await asyncio.gather(send_task, receive_task)
asyncio.run(main())

View File

@ -1,25 +1,31 @@
import asyncio
import websockets
import json
import time
connected_clients = set()
validTokens = "123456"
def sendData(websocket):
while True:
websocket.send("Heartbeat")
print("Heartbeat send")
time.sleep(5)
async def handler(websocket, path):
connected_clients.add(websocket)
try:
print("New client connected to the server")
if path != "/":
print("client disconnected")
await websocket.send(json.dumps({"error": "Invalid path", "code": 9000}))
await websocket.close()
return
connected_clients.add(websocket)
try :
async for message in websocket:
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)
print(f"Message reçu : {message}")
except websockets.exceptions.ConnectionClosed as e:
print(f"Connexion fermée: {e}")
finally:
print("Client déconnecté")
connected_clients.remove(websocket)
print("Client disconnected with error :", e)
sendData(websocket)
try:
start_server = websockets.serve(handler, "localhost", 8000, reuse_address=True)
@ -27,4 +33,5 @@ except OSError as e:
print(f"Error: {e}")
exit(1)
asyncio.get_event_loop().run_until_complete(start_server)
print("Server started")
asyncio.get_event_loop().run_forever()