Skip to content

Instantly share code, notes, and snippets.

@alex-eri
Created October 6, 2020 00:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alex-eri/9d63a6356c5de3d590a99707e6983a4c to your computer and use it in GitHub Desktop.
Save alex-eri/9d63a6356c5de3d590a99707e6983a4c to your computer and use it in GitHub Desktop.
class Data:
def __init__(self):
self.state = {}
self.cond = asyncio.Condition()
async def clock_waiter(m, cb):
while True:
try:
async with m.cond:
await m.cond.wait()
await cb(m.state)
except asyncio.CancelledError:
pass
except Exception as e:
logging.warning(e)
@routes.get('/ws')
async def websocket_handler(request):
ws = web.WebSocketResponse(heartbeat=10)
await ws.prepare(request)
m = request.app['clocked']
point_task = asyncio.get_running_loop().create_task(
point_waiter(m, ws.send_json)
)
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
pass
elif msg.type == aiohttp.WSMsgType.ERROR:
logging.debug(
'ws connection closed with exception %s', ws.exception()
)
logging.debug('websocket connection closed')
point_task.cancel()
return ws
async def clock(m):
while asyncio.sleep(2):
async with m.cond:
m.state = {time: time.time()}
m.cond.notify_all()
app['tracks'] = Data()
loop.create_task(clock(app['clocked']))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment