initial WSRouter implementation

This commit is contained in:
AAGaming
2022-11-25 23:19:21 -05:00
committed by marios8543
parent 8f299a90dc
commit 4a9b45b98e
2 changed files with 50 additions and 20 deletions
+46
View File
@@ -0,0 +1,46 @@
from logging import getLogger
from aiohttp import web
class WSRouter:
def __init__(self) -> None:
self.ws = None
self.routes = {}
self.logger = getLogger("WSRouter")
async def add_routes(self, routes):
self.routes.update(routes)
async def handle(self, request):
self.logger.debug('Websocket connection starting')
ws = web.WebSocketResponse()
await ws.prepare(request)
self.logger.debug('Websocket connection ready')
self.ws = ws
try:
async for msg in ws:
self.logger.debug(msg)
if msg.type == aiohttp.WSMsgType.TEXT:
self.logger.debug(msg.data)
if msg.data == 'close':
# DO NOT RELY ON THIS!
break
else:
# do stuff with the message
data = msg.json()
if self.routes[data.route]:
res = await self.routes[data.route](data.data)
finally:
try:
await ws.close()
except:
pass
self.logger.debug('Websocket connection closed')
return ws
async def write(self, dta: Dict[str, any]):
await self.ws.send_json(dta)