插槽在运行心跳时侦听事件

时间:2017-11-17 19:16:36

标签: python asynchronous concurrency websocket

我正在尝试为socket事件设置一个侦听器,同时在后台发送ping消息。

message received个事件会在下一次ping完成后触发,但。似乎有阻碍的东西。

这是我正在运行的代码的模型。

import asyncio
import websockets

message = "First Message"
ping = "ping"
url = 'www.socketurl.com'


async def consumer_handler(websocket):
    message = await websocket.recv()
    if message:
        print(message)

async def pingFunc(socket):
    await asyncio.sleep(4)
    await socket.send(ping)

async def connect(uri):
    async with websockets.connect(uri,timeout=5) as websocket:
        await websocket.send(message) #send hello message that returns a few pieces of info
        while True: 
            await consumer_handler(websocket) #wait for messages and handle them
            await pingFunc(websocket) #keep the connection alive

loop = asyncio.get_event_loop()

loop.run_until_complete(
    connect(url)
)

0 个答案:

没有答案