简体   繁体   中英

How to rewrite aiohttp websocket handler to sanic?

I have the following websocket handler in my aiohttp project:

async def websocket_handler(request):
     ws = web.WebSocketResponse()
     await ws.prepare(request)
     request.app['websockets'].append(ws)

     async for msg in ws:
         if msg.type == aiohttp.WSMsgType.TEXT:
             if msg.data == 'close':
                 await ws.close()

         elif msg.type == aiohttp.WSMsgType.ERROR:
             logger.info('ws connection closed with exception %s' %
                            ws.exception())

     request.app['websockets'].remove(ws)
     return ws

But now I wanna to switch to sanic framework. How to rewrite this method? I don't understand how to do this from this tutorial

@bp.websocket('/websocket_handler')
    async def websocket_handler(_, ws):
        self.app['web_socket'].append(ws)
        while True:
            try:
                await ws.recv()
            except ConnectionClosed:
                break

        self.app['web_socket'].remove(ws)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM