你如何在Twisted中的协议之间共享状态?

时间:2014-03-11 22:54:23

标签: python twisted pyzmq autobahn

我有两个协议,一个是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()

1 个答案:

答案 0 :(得分:0)

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

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