Python 带有异步计时器的异步 websocket 客户端
Python async websocket client with async timer
我需要一个很长的 运行ning websocket 客户端来接收来自 websocket 服务器的推送消息,我需要监视客户端的连接状态:如果连接断开,我需要找出来。
我的方法是定期记录一个常量字符串,并在未检测到日志消息时触发警报。
我的想法:1) 有一个响应不规则传入消息的 websocket 客户端。并且 2) 同时具有循环,当 websocket 客户端抛出 ConnectionClosed 异常时停止记录消息。
我对新的 3.5 异步语法很感兴趣。 This websocket implementation is specifically based on the asyncio. The 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
完成。
只需两步即可解决:
- 使用
asyncio.ensure_future
调度协程(立即运行而不等待结果),每个返回任务。
- 等待任务完成
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()
]))
我需要一个很长的 运行ning websocket 客户端来接收来自 websocket 服务器的推送消息,我需要监视客户端的连接状态:如果连接断开,我需要找出来。
我的方法是定期记录一个常量字符串,并在未检测到日志消息时触发警报。
我的想法:1) 有一个响应不规则传入消息的 websocket 客户端。并且 2) 同时具有循环,当 websocket 客户端抛出 ConnectionClosed 异常时停止记录消息。
我对新的 3.5 异步语法很感兴趣。 This websocket implementation is specifically based on the asyncio. The 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
完成。
只需两步即可解决:
- 使用
asyncio.ensure_future
调度协程(立即运行而不等待结果),每个返回任务。 - 等待任务完成
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()
]))