考虑(其中 queueasyncio.Queue ,我正在使用与标准库中的 asyncio 相同的服务器接口的asyncio websockets库):

async def handler(websocket: websockets.WebSocketServerProtocol, path):
    while True:
        data = await queue.get()
        await websocket.send(data)

我发现的是 ConnectionClosed 异常(当客户端断开连接并且也用于服务器关闭时触发)只会在我们等待 send() 时在循环内引发 . 在websocket客户端断开连接后,这可能会发生 long ,因为我们将花费大部分时间等待 queue.get() .

此外,我正在尝试实现服务器的正常关闭 . 该代码看起来非常类似于标准

server.close()
loop.run_until_complete(server.wait_closed())

问题是我的websocket处理程序,即 handler() ,仍然继续在 queue 上等待更多数据,然后再提出 wait_closed() 放在事件循环上的异常 .

我的 question :引入使用 wait_for() 使 handler() 函数对这些管理事件更具响应性是否正确:

async def handler(websocket: websockets.WebSocketServerProtocol, path):
    while True:
        try:
            data = await loop.wait_for(queue.get(), 5.0)  # 5 seconds
            await websocket.send(data)
        except asyncio.TimeoutError:
            logging.debug('Refreshing the loop')

我在网上发现的大多数asyncio示例都非常简单,似乎并没有涵盖这些问题 .

我还可以在关机序列期间将垃圾放在队列中,这将允许引发异常,但这无助于更早地捕获客户端断开连接 .

任何带有示例的好参考都将非常感激 . 我发现官方的asyncio文档有点简洁 .