【问题标题】:How do you share state between protocols in Twisted?你如何在 Twisted 中的协议之间共享状态?
【发布时间】:2014-03-11 22:54:23
【问题描述】:

我有两种协议,一种是 WebSocket 服务器,另一种是 ZeroMQ 拉式套接字。我想将收到我的 ZMQ 的东西转发到 WebSocket。这可能吗?

class WebSocketProtocol(WebSocketServerProtocol):

    def onMessage(self, msg, binary):
        print "Received: ", msg, binary
        self.sendMessage(msg, binary)


class MyProto(ZmqPullConnection):

    def onPull(self, message):
        print "Recevied: ", message
        # How to I call sendMessage(message) from here?

if __name__ == '__main__':
    zf = ZmqFactory()
    e = ZmqEndpoint("bind", "tcp://127.0.0.1:5500")   
    s = MyProto(zf, e)

    factory_ws = WebSocketServerFactory("ws://127.0.0.1:9500/echo", debug = False)
    factory_ws.protocol = WebSocketProtocol
    listenWS(factory_ws)
    reactor.run()

【问题讨论】:

  • 您想将 0MQ 事件广播到每个 WebSocket 客户端还是特定的客户端?如果是后者,如何识别“特定”的?

标签: python twisted pyzmq autobahn


【解决方案1】:

查看this 示例。新的WebSocketServerProtocol 实例在WebSocketServerFactory 上注册自己。然后后者有一个broadcast 方法在所有当前连接的客户端上调度一个事件。

鉴于此,您只需将对 WebSocketServerFactory 的引用放到您的 MyProto 实例 (s.factory_ws = factory_ws) 上,然后从您的 0MQ 原型调用 broadcast 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-19
    • 2016-11-02
    • 1970-01-01
    • 2010-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多