微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在运行时调用高速公路 websocketclientprotocol 对象上的函数?

如何解决如何在运行时调用高速公路 websocketclientprotocol 对象上的函数?

我正在构建一个 API,该 API 具有通过 websockets 进行通信的组件,目前使用高速公路库。我试图弄清楚如何从他们的 github(特别是 this example修改一个示例客户端,这样我就可以向客户端添加额外的功能,我可以从外部调用,类似于下面的修改版本他们的例子,这是我目前最好的尝试。我遇到的两个主要问题:

  1. 如何获取高速公路正在使用的协议类的实例?我似乎可以在我的示例中的 _,client = loop.run_until_complete(coro) 行中获得对它的引用,但它似乎对我不起作用。

  2. 假设问题 1 有解决方案,那么在示例底部运行高速公路客户端和 while True 循环的最佳方法是什么?我应该在线程中抛出 loop.run_forever() 行吗?

这是我在他们的 github 上修改后的 example 版本,我想做什么:

import asyncio
import random

from autobahn.asyncio.websocket import WebSocketClientProtocol,WebSocketClientFactory


class MyClientProtocol(WebSocketClientProtocol):

    def __init__(self):
        self.super().__init__()
        self.state = -1

    def onConnect(self,response):
        print("Server connected: {0}".format(response.peer))

    async def onopen(self):
        print("WebSocket connection open.")

        # start sending messages every second ..
        while True:
            self.sendMessage("Hello,world!".encode('utf8'))
            self.sendMessage(b"\x00\x01\x03\x04",isBinary=True)
            await asyncio.sleep(1)

    def onMessage(self,payload,isBinary):
        if isBinary:
            print("Binary message received: {0} bytes".format(len(payload)))
        else:
            print("Text message received: {0}".format(payload.decode('utf8')))

    def onClose(self,wasClean,code,reason):
        print("WebSocket connection closed: {0}".format(reason))

    # new setter function I want to be able to use
    def sendNextAction(self,next_action: int):
        print("Next action is {}".format(next_action))
        self.state += next_action

    # new getter function I want to be able to use
    def getCurrentState(self):
        return self.state

if __name__ == '__main__':

    factory = WebSocketClientFactory("ws://127.0.0.1:9000")
    factory.protocol = MyClientProtocol

    loop = asyncio.get_event_loop()
    coro = loop.create_connection(factory,'127.0.0.1',9000)
    _,client = loop.run_until_complete(coro)  # my attempt to get client reference
    loop.run_forever()
    loop.close()

    # this is how I want to interact with the MyClientProtocol outside of it
    actions = [1,2,3,4,5]
    while True:
        client.sendNextAction(random.choice(actions))
        curr_state = client.getCurrentState()
        print("Current state is Now {}".format(curr_state))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?