tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

counter.py (1290B)


      1 #!/usr/bin/env python
      2 
      3 import asyncio
      4 import json
      5 import logging
      6 import websockets
      7 
      8 logging.basicConfig()
      9 
     10 USERS = set()
     11 
     12 VALUE = 0
     13 
     14 def users_event():
     15    return json.dumps({"type": "users", "count": len(USERS)})
     16 
     17 def value_event():
     18    return json.dumps({"type": "value", "value": VALUE})
     19 
     20 async def counter(websocket):
     21    global USERS, VALUE
     22    try:
     23        # Register user
     24        USERS.add(websocket)
     25        websockets.broadcast(USERS, users_event())
     26        # Send current state to user
     27        await websocket.send(value_event())
     28        # Manage state changes
     29        async for message in websocket:
     30            event = json.loads(message)
     31            if event["action"] == "minus":
     32                VALUE -= 1
     33                websockets.broadcast(USERS, value_event())
     34            elif event["action"] == "plus":
     35                VALUE += 1
     36                websockets.broadcast(USERS, value_event())
     37            else:
     38                logging.error("unsupported event: %s", event)
     39    finally:
     40        # Unregister user
     41        USERS.remove(websocket)
     42        websockets.broadcast(USERS, users_event())
     43 
     44 async def main():
     45    async with websockets.serve(counter, "localhost", 6789):
     46        await asyncio.Future()  # run forever
     47 
     48 if __name__ == "__main__":
     49    asyncio.run(main())