Created
October 6, 2020 00:15
-
-
Save alex-eri/9d63a6356c5de3d590a99707e6983a4c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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