Tornado websocket 客户端:如何异步 on_message? (从未等待协程)

Posted

技术标签:

【中文标题】Tornado websocket 客户端:如何异步 on_message? (从未等待协程)【英文标题】:Tornado websocket client: how to async on_message? (coroutine was never awaited) 【发布时间】:2020-05-30 12:40:16 【问题描述】:

如何让 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

【问题讨论】:

【参考方案1】:

on_message_callback 应该是常规函数,而不是协程。当人们使用回调而不是协程时,它旨在用于旧式代码。

对于较新的异步样式代码,您不需要此回调。你可以这样做:

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)

【讨论】:

谢谢 xyres,它就像一个魅力,你让我开心!

以上是关于Tornado websocket 客户端:如何异步 on_message? (从未等待协程)的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Tornado 监听来自多个地方的传入 websocket 消息?

Tornado websocket 客户端:如何异步 on_message? (从未等待协程)

Tornado-长轮询_webSocket

使用 tornado websockets 传递消息

tornado+websocket+mongodb实现在线视屏文字聊天

Python下tornado架构websocket简介