python - 已解决:异步 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 回复,它会断开我的连接。
泰,丹尼
解决方案
推荐阅读
- iis - IIS 看不到证书
- woocommerce - WooCommerce rest api 访问因 httpWebRequest 失败
- selenium - 当我在画布上绘制某些东西时,Selenium W3C 方言创建问题
- microsoft-graph-api - Microsoft Graph API SDK for SharePoint 用于查询文件
- flutter - 图标值未随提供程序和 sqflite 更新而颤动
- r - 在 R 中,当它们都是非常相似的数值向量时,为什么一个函数工作而另一个不工作?
- javascript - TypeError:无法读取未定义的属性(读取“createdTimestamp”)
- statistics - 关于如何在我的学习中使用多层次建模的概念问题
- python - TensorFlow urllib.error.URLError:
- postgresql - 一个表中的日期在另一个表中的日期之前 - Postgres