2017-09-20 73 views
3

我有以下我aiohttp項目websocket handler如何重寫aiohttp websocket處理程序sanic?

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 

但現在我想切換到sanic框架。如何重寫這個方法?我不明白該怎麼做tutorial

回答

0
@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) 
相關問題