Tornado websocket客户端:如何异步on_message?(coroutine从未被等待过)

问题描述 投票:0回答:1

如何使on_message函数在Tornado WebSocketClient中异步工作?

我想我需要等待on_message函数,但我不知道如何。

或者说,在我尝试实现异步WebSocketClient的方式上是否存在根本性的误区?

import tornado.websocket
from tornado.queues import Queue
from tornado import gen
import json


q = Queue()

class WebsocketClient():

    def __init__(self, url, connections):
        self.url = url
        self.connections = connections
        print("CLIENT started")
        print("CLIENT initial connections: ", len(self.connections))

    async def send_message(self):
        async for message in q:
            try:
                msg = json.loads(message)
                print(message)
                await gen.sleep(0.001)
            finally:
                q.task_done()

    async def update_connections(self, connections):
        self.connections = connections
        print("CLIENT updated connections: ", len(self.connections))

    async def on_message(self, message):
        await q.put(message)
        await gen.sleep(0.001)

    async def connect(self):
        client = await tornado.websocket.websocket_connect(url=self.url, on_message_callback=self.on_message)
RuntimeWarning: coroutine 'WebsocketClient.on_message' was never awaited
  self._on_message_callback(message)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
python-3.x asynchronous websocket client tornado
1个回答
0
投票

on_message_callback 应该是一个常规函数,而不是一个coroutine。而且它是为了在旧式代码中使用,当时人们使用回调而不是coroutine。

对于新的async风格的代码,你不需要这个回调。你可以直接这样做。

async def connect(self):
    client = await tornado.websocket.websocket_connect(url=self.url)

    while True:
        message = await client.read_message()

        if message is None:
            # None message means the connection was closed
            break

        print("Message received:", message)
        await q.put(message)
        await gen.sleep(0.001)
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.