Module livechat :
- Style finish - Just button "new conversation" not ready - Starting websocket but its
This commit is contained in:
23
site/module_livechat/server/a.py
Normal file
23
site/module_livechat/server/a.py
Normal file
@ -0,0 +1,23 @@
|
||||
import asyncio
|
||||
import websockets
|
||||
|
||||
async def send_messages(websocket):
|
||||
while True:
|
||||
message = input("Enter message to send: ")
|
||||
await websocket.send(message)
|
||||
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)
|
||||
|
||||
# Démarrer le client
|
||||
asyncio.run(main())
|
28
site/module_livechat/server/main.py
Normal file
28
site/module_livechat/server/main.py
Normal file
@ -0,0 +1,28 @@
|
||||
import asyncio
|
||||
import websockets
|
||||
|
||||
connected_clients = set()
|
||||
validTokens = "123456"
|
||||
|
||||
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)
|
||||
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)
|
||||
asyncio.get_event_loop().run_until_complete(start_server)
|
||||
asyncio.get_event_loop().run_forever()
|
Reference in New Issue
Block a user