forked from cs160-summer-2019/p3-websockets-harperKKK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
echoserver.py
35 lines (27 loc) · 853 Bytes
/
echoserver.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
import asyncio
import json
import logging
import websockets
logging.basicConfig()
USERS = set()
def users_event():
return json.dumps({'type': 'users', 'count': len(USERS)})
async def notify_message(message):
if USERS:
await asyncio.wait([user.send(message) for user in USERS])
async def register(websocket):
USERS.add(websocket)
async def unregister(websocket):
USERS.remove(websocket)
async def something(websocket, path):
# register(websocket) sends user_event() to websocket
await register(websocket)
try:
# await websocket.send("hi")
async for message in websocket:
await notify_message(message)
finally:
await unregister(websocket)
asyncio.get_event_loop().run_until_complete(
websockets.serve(something, '0.0.0.0', 8765))
asyncio.get_event_loop().run_forever()