-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
56 lines (43 loc) · 1.44 KB
/
main.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
import asyncio
import json
import logging
import websockets
logging.basicConfig()
USERS = []
async def notify_users(message):
if USERS: # asyncio.wait doesn't accept an empty list
await asyncio.wait([user["websocket"].send(message) for user in USERS])
async def register(websocket, user):
USERS.append({"websocket":websocket,"user":user})
message = {
"message":f"User {user} joined the chat.",
"type": "register",
"user": user
}
print(message, websocket)
await notify_users(json.dumps(message))
async def unregister(websocket, user):
USERS.remove({"websocket":websocket,"user":user})
message = {
"message":f"User {user} left the chat.",
"type": "unregister",
"user": user
}
print(message)
await notify_users(json.dumps(message))
async def counter(websocket, path):
user = path[1:]
# register(websocket) sends user_event() to websocket
await register(websocket, user)
try:
#await websocket.send(state_event())
async for message in websocket:
message_json = json.loads(message)
message_json["user"] = user
await notify_users(json.dumps(message_json))
finally:
await unregister(websocket, user)
if __name__ == '__main__':
start_server = websockets.serve(counter, None, 6789)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()