-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleEndServer.py
51 lines (37 loc) · 1.26 KB
/
middleEndServer.py
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
43
44
45
46
47
48
49
50
51
import asyncio
import json
import socket
from colors import *
from confidentials import *
import websockets
def getData(jsonObject):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((Confidentials.HOST, Confidentials.PORT))
jsonObject = json.dumps(jsonObject)
s.sendall(bytes(jsonObject, encoding="utf-8"))
data = s.recv(1024)
s.close()
return data
async def handler(websocket):
while True:
try:
message = await websocket.recv()
except websockets.ConnectionClosedOK:
break
jsonObject = json.loads(message)
if jsonObject:
print(f"{Yellow}", "Fetching Data", jsonObject)
response = getData(jsonObject)
print(f"{Green}", "Fetching Successfull")
await websocket.send(response.decode("utf-8"))
def sendResponse(response):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect(("localhost", 8001))
jsonObject = json.dumps(response)
s.sendall(bytes(jsonObject, encoding="utf-8"))
s.close()
async def main():
async with websockets.serve(handler, "", 8001):
await asyncio.Future() # run forever
if __name__ == "__main__":
asyncio.run(main())