【发布时间】:2018-04-19 14:47:07
【问题描述】:
我的 WebSocket 服务器实现是对外开放的,但是客户端需要在连接建立后发送一个身份验证消息,否则服务器应该关闭连接。
如何在 aiohttp 中实现它?看来,我需要做以下事情:
为每个套接字连接创建一个
on_open方法:我找不到创建此类事件的方法(类似于 Tornado 中的 on_open)。-
创建一个计时器:可以使用主事件循环的 asyncio 的
sleep或call_back方法。但是我找不到将 WebSocketResponse 发送到回调函数的方法:await asyncio.sleep(10, timer, loop=request.app.loop) 如果未通过身份验证则关闭连接
这是我之前使用 Tornado 时的情况:
def open(self, *args, **kwargs):
self.timeout = ioloop.IOLoop.instance().add_timeout(
datetime.timedelta(seconds=60),
self._close_on_timeout
)
def remove_timeout_timer(self):
ioloop.IOLoop.instance().remove_timeout(self.timeout)
self.timeout = None
def on_message(self, message):
if message = 'AUTHENTICATE':
self.authenticated = True
self.remove_timeout_timer
def _close_on_timeout(self):
if not self.authenticated:
if self.ws_connection:
self.close()
这是我使用 aiohttp 设置计时器的内容:
async def ensure_client_logged(ws):
await asyncio.sleep(3) # wait 3 seconds
await ws.send_str('hello')
async def ws_handler(request):
ws = web.WebSocketResponse()
asyncio.ensure_future(ensure_client_logged(ws), loop=request.app.loop)
但代码以阻塞方式运行,这意味着服务器在休眠时变得无响应。
有人可以指点我正确的方向吗?
【问题讨论】:
-
async with async_timeout.timeout(3): await ws.receive()
标签: python-3.x python-asyncio aiohttp