python 异步socket,Python异步websocket客户端与async tim

  • Post author:
  • Post category:python

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

我的方法是定期记录一个常量字符串,如果没有检测到日志消息,就会触发警报。在

我的想法是:1)有一个websocket客户机来响应不规则的传入消息。同时,有一个循环,当websocket客户机抛出ConnectionClosed execption时停止记录消息。在

我对新的3.5异步语法很感兴趣。This websocket实现是专门基于异步的。文档中的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())