gpt4 book ai didi

带有异步定时器的 Python 异步 websocket 客户端

转载 作者:太空宇宙 更新时间:2023-11-03 14:13:14 25 4
gpt4 key购买 nike

我需要一个长时间运行的 websocket 客户端来接收来自 websocket 服务器的推送消息,我需要监视客户端的连接状态:如果连接断开,我需要找出来。

我的方法是定期记录一个常量字符串,并在未检测到日志消息时触发警报。

我的想法:1) 有一个响应不规则传入消息的 websocket 客户端。并且 2) 同时具有在 websocket 客户端抛出 ConnectionClosed 异常时停止记录消息的循环。

我对新的 3.5 异步语法很感兴趣。 This websocket实现是专门基于 asyncio 的。 client在文档中看起来完全像我需要的。

但是,我不知道如何添加第二个协程来执行我的日志语句并且当 websocket 连接抛出 ConnectionClosed 时以某种方式停止。

这是开始对话的东西,但它不起作用,因为 alive 方法阻塞了事件循环。我正在寻找的是同时运行这两种方法的优雅解决方案。

#!/usr/bin/env python

import asyncio
import logging

import websockets

logger = logging.getLogger(__name__)

is_alive = True


async def alive():
while is_alive:
logger.info('alive')
await asyncio.sleep(300)


async def async_processing():
async with websockets.connect('ws://localhost:8765') as websocket:
while True:
try:
message = await websocket.recv()
print(message)

except websockets.exceptions.ConnectionClosed:
print('ConnectionClosed')
is_alive = False
break


asyncio.get_event_loop().run_until_complete(alive())
asyncio.get_event_loop().run_until_complete(async_processing())

最佳答案

实际上 run_until_complete 阻塞在这里,因为它一直等到 alive 完成。

您可以通过 2 个步骤解决它:

  1. 使用 asyncio.ensure_future 安排协程(立即运行而不等待结果),每个返回任务。
  2. 等待任务完成 asyncio.wait

代码如下:

tasks = [
asyncio.ensure_future(alive()),
asyncio.ensure_future(async_processing())
]
asyncio.get_event_loop().run_until_complete(asyncio.wait(tasks))

正如@Vincent 提到的wait 接受任务,所以ensure_future 是不必要的:

asyncio.get_event_loop().run_until_complete(asyncio.wait([   
alive(),
async_processing()
]))

关于带有异步定时器的 Python 异步 websocket 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35529754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com