-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWebsocketClient.py
75 lines (55 loc) · 2.44 KB
/
WebsocketClient.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import asyncio
import websockets
import time
from random import randint
import json
from PrintColors import bcolors
class client:
def __init__(self, ID):
self.ID = ID
self.others = []
def start(self):
asyncio.run(self.JoinAndVibe())
async def JoinAndVibe(self):
uri="ws://localhost:8080"
async with websockets.connect(uri) as websocket:
await websocket.send(self.genMsg("Join", "Server", msg=self.ID))
async for message in websocket:
closed = await self.Response(websocket, message)
if closed:
break
async def Response(self, websocket, message):
message = json.loads(message)
while(message["Type"] == "PONG" or message["Type"] == "Welcome" or message["Type"] == "Command" or message["Type"] == "New_User"):
time.sleep(2)
if message["Type"] == "Welcome":
print(bcolors.OKBLUE + str(message) + bcolors.ENDC)
for i in message["Message"]:
self.others.append(i)
print("Connection Successful\n")
print(self.others)
print("\n")
elif message["Type"] == "New_User":
print("We got a new User")
self.others.append(message["Message"])
print(bcolors.WARNING + str(self.others) + bcolors.ENDC)
elif message["Type"] == "Command":
print(message["Message"])
#if(randint(0, 10) == 2 and len(self.others) > 0):
#await websocket.send(self.genMsg("Command", self.others[0], msg="Hey!"))
if randint(0, 20) == 5:
print(bcolors.BOLD + bcolors.FAIL + "About to close the websocket!" + bcolors.ENDC + bcolors.ENDC)
await websocket.send(self.genMsg("Close", "Serveer"))
return True
await websocket.send(self.genMsg("PING", "Server"))
print(bcolors.HEADER + "PING" + bcolors.ENDC)
message = await websocket.recv()
message = json.loads(message)
if message["Type"] == "Close":
return True
quit()
def genMsg(self, Tpe, Recvr, msg="PING"):
newMsg = {"Type": Tpe, "Sender": self.ID, "Recipient": Recvr, "Message": msg}
return json.dumps(newMsg)
async def main(self):
await asyncio.gather(self.JoinAndVibe())