-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocketserver.py
executable file
·81 lines (59 loc) · 2.15 KB
/
websocketserver.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
76
77
78
79
80
81
#!/usr/bin/env python
import asyncio
import json
# `pip install websockets`
import websockets
# The websockets docs are also the source for this code. See
# https://websockets.readthedocs.io/en/stable/howto/quickstart.html#manage-application-state.
# I modified the code slightly, to also let the server independently send
# messages to the clients, to denote the full duplex nature of websockets.
USERS = set()
COUNTER = 0
async def broadcast(users, data, desc):
if users:
await asyncio.wait(
[asyncio.create_task(send(user, data, desc)) for user in users]
)
async def send(user, data, desc):
await user.send(json.dumps({"data": data, "desc": desc}))
async def server_messages():
# This is the place where we do server side stuff and send messages to the
# connected clients, if needed.
global COUNTER
while True:
await asyncio.sleep(2)
COUNTER += 1
await broadcast(USERS, COUNTER, "counter")
def user_messages():
return websockets.serve(handle_connection, "localhost", PORT)
def parse(message):
info = json.loads(message)
return info["data"], info["desc"]
async def handle_connection(user):
global USERS, COUNTER
try:
USERS.add(user)
await broadcast(USERS, len(USERS), "amount_users")
await send(user, COUNTER, "counter")
async for message in user:
# this is the place where we handle messages sent by a connected
# client. This is done independently for each client.
data, desc = parse(message)
match desc:
case "update_counter":
COUNTER = COUNTER + data
await broadcast(USERS, COUNTER, "counter")
case other:
print(f'unsupported: "{desc}": {data}')
finally:
USERS.remove(user)
await broadcast(USERS, len(USERS), "amount_users")
PORT = 6789
async def main():
await asyncio.gather(server_messages(), user_messages())
if __name__ == "__main__":
print(f"Listening on ws://localhost:{PORT}/")
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\nbye")