【问题标题】:Bidirectional communiation with websockets in QuartQuart 中与 websocket 的双向通信
【发布时间】:2020-06-29 03:17:07
【问题描述】:

我希望能够在 Quart 中使用 WebSocket 来接收发送的任何消息,并发送我可能需要发送的任何消息。无法保证消息会在发送和接收之间交替。

例如,Quart's tutorial page on WebSockets 具有以下 sn-p:

@app.websocket('/api/v2/ws')
@collect_websocket
async def ws(queue):
    while True:
        data = await queue.get()
        await websocket.send(data)

不知何故,我想修改while True循环中的代码,以便我可以检查是否有任何数据要接收,但如果没有,我将改为检查队列。

我希望只有在有东西要接收的情况下才能在套接字上等待接收(如果receive 方法中有一个timeout 参数,也许可以实现),但这不是一个选项.

那么,我怎样才能await WebSocket 进行更新,同时await 使用其他内容进行更新

【问题讨论】:

    标签: websocket async-await python-asyncio quart


    【解决方案1】:

    Quart 的作者在帖子Websockets in Quart 中回答了这个问题,其中包含一个我稍微修改过的 sn-p 以获得以下内容:

    import asyncio
    
    from quart import copy_current_websocket_context, Quart, websocket
    
    app = Quart(__name__)
    
    @app.websocket('/ws')
    async def ws():
    
        async def consumer():
            while True:
                data = await websocket.receive()
    
        async def producer():
            while True:
                await asyncio.sleep(1)
                await websocket.send(b'Message')
    
        consumer_task = asyncio.ensure_future(consumer())
        producer_task = asyncio.ensure_future(producer())
        try:
            await asyncio.gather(consumer_task, producer_task)
        finally:
            consumer_task.cancel()
            producer_task.cancel()
    

    sn-p 使用自己的 while True 循环创建两个不同的异步函数。然后,Python 的asyncio.ensure_future 用于创建两个不同的Tasks 来处理。最后,调用asyncio.gather 来同时评估任务。

    通过在ws 的定义中定义两个任务,它们充当闭包,这意味着它们可以访问websocket“特殊”全局对象,这仅在ws 函数内部有意义。如果您想在 ws 函数的主体之外定义这些函数,可能是因为您需要从其他地方调用它们,您可以在将它们传递给 ensure_future 时使用 Quart 中的 copy_current_websocket_context 函数:

    consumer_task = asyncio.ensure_future(
        copy_current_websocket_context(consumer)()
    )
    

    【讨论】:

      猜你喜欢
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2019-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多