首页 > 解决方案 > 已解决:异步 websockets while 循环逻辑

问题描述

蟒蛇新手。我正在尝试做一些事情,但我不知道我的逻辑是否合法。

所以我有一个 weksocket (ws),为了让这个 websocket 保持连接,它需要每分钟,当它收到“ping”时,我应该回复“pong:

所以我做了这样的事情:

async def run():
    prepare_env("test")
    async with websockets.connect(wss_request_url, ssl=True) as ws:
        while True:
            msg = await ws.recv()
            if msg == "ping":
                print("received: ping")
                await send(ws, "pong")
            else:
                response = json.loads(msg)
                if "something" in response:
                     await handle_message(ws, response)
                else:
                     print(f"received:{response}")
asyncio.get_event_loop().run_until_complete(run())

基于响应中的“某事”,我在某个时候有一个函数(verify_price),当价格发生变化时,该函数需要在休息 API 中进行验证。

async def verify_price(ws, old_price):
    price_changed = False
    while price_changed is False:
        price = get_new_price()
        if price <> old_price:
            await send(ws, "pricechanged")
            price_changed = True

我的问题是,当我在这个 while 循环中,等待价格变化时,如果我收到另一个 ping,它不会用 pong 回复,它会断开我的连接。

泰,丹尼

标签: pythonloopswebsocketasync-await

解决方案


推荐阅读