-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
42 lines (34 loc) · 1.24 KB
/
server.py
File metadata and controls
42 lines (34 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import asyncio
import json
import websockets
clients = {
'sender': None,
'receiver': None,
'sender1': None
}
async def handler(websocket, path):
if path == "/sender":
clients['sender'] = websocket
elif path == "/receiver":
clients['receiver'] = websocket
elif path == "/sender1":
clients['sender1'] = websocket
async for message in websocket:
data = json.loads(message)
print(f"Received data from {path}: {data}")
# Send received data to the receiver client
if clients['receiver']:
response = json.dumps({"received_from_sender": data})
await clients['receiver'].send(response)
print("Sent data to receiver")
# Send acknowledgment to the sender client
if clients['sender'] or clients['sender1']:
ack = json.dumps({"response": "Data received"})
await clients['sender'].send(ack)
print("Sent acknowledgment to sender")
start_server = websockets.serve(handler, "localhost", 8765)
async def main():
await start_server
print("\033[92mServer started and ready at ws://localhost:8765\033[0m")
await asyncio.Future() # Run forever
asyncio.get_event_loop().run_until_complete(main())