【问题标题】:sendMessage from outside in autobahn running in separate thread by using "asyncio"使用“asyncio”从高速公路外部发送消息,在单独的线程中运行
【发布时间】:2017-07-06 15:43:18
【问题描述】:

我想从 MyServerProtocol 类之外调用 sendMessage 方法并向服务器发送消息。 answare 非常类似于this 但我需要使用 asyncio 而不是twisted

有人可以建议我一个解决方案吗?从this 派生的示例也将不胜感激 谢谢。

【问题讨论】:

    标签: python multithreading python-asyncio autobahn


    【解决方案1】:

    事件循环的call_soon_threadsafe 函数就是为此而生的。

    from autobahn.asyncio.websocket import WebSocketServerProtocol, \
        WebSocketServerFactory
    
    
    class MyServerProtocol(WebSocketServerProtocol):
    
        loop = None
    
        def onConnect(self, request):
            print("Client connecting: {0}".format(request.peer))
    
        def onOpen(self):
            print("WebSocket connection open.")
    
        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))
    
        @classmethod
        def broadcast_message(cls, data):
            payload = json.dumps(data, ensure_ascii = False).encode('utf8')
            for c in set(cls.connections):
                self.loop.call_soon_threadsafe(cls.sendMessage, c, payload)
    
    
    factory = WebSocketServerFactory(u"ws://127.0.0.1:9000")
    factory.protocol = MyServerProtocol
    
    loop = asyncio.get_event_loop()
    MyServerProtocol.loop = loop
    coro = loop.create_server(factory, '0.0.0.0', 9000)
    server = loop.run_until_complete(coro)
    
        try:
            loop.run_forever()
        except KeyboardInterrupt:
            pass
        finally:
            server.close()
    loop.close()
    

    然后从另一个线程简单地调用

    MyServerProtocol.broadcast_message(payload)
    

    【讨论】:

    • 我正在尝试使用此答案从 MQTT 订阅者发送 Websocket 消息,但我遇到了一个一致的问题,call_soon_threadsafe 似乎正在创建......“部分”实例,缺少父类 WebSocketClientProtocolWebSocketProtocol 的所有字段。我应该根据这个问题打开一个新问题吗?
    猜你喜欢
    • 2015-05-02
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多