Tornado WebSocket客户端:如何在消息上同步?(协程从未被期待过) [英] Tornado websocket client: how to async on_message? (coroutine was never awaited)

查看:0
本文介绍了Tornado WebSocket客户端:如何在消息上同步?(协程从未被期待过)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

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)

这篇关于Tornado WebSocket客户端:如何在消息上同步?(协程从未被期待过)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆