简体   繁体   English

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

[英]How do you share state between protocols in Twisted?

I have two protocols, one a WebSocket server the other a ZeroMQ pull socket. 我有两个协议,一个是WebSocket服务器,另一个是ZeroMQ拉套接字。 I want to forward things received my ZMQ to the WebSocket. 我想将收到的ZMQ的内容转发到WebSocket。 Is this possible? 这可能吗?

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()

Have a look at this example. 这个例子。 New WebSocketServerProtocol instances register themselfes on the WebSocketServerFactory . WebSocketServerProtocol情况登记在themselfes WebSocketServerFactory The latter then has a broadcast method to dispatch an event on all currently connected clients. 后者则具有一种broadcast方法,可在所有当前连接的客户端上调度事件。

Given that, all you need is put a reference to the WebSocketServerFactory onto your MyProto instance ( s.factory_ws = factory_ws ) and then call the broadcast method from your 0MQ proto. 鉴于此,您所需MyProto就是将对WebSocketServerFactory的引用放到MyProto实例上( s.factory_ws = factory_ws ),然后从0MQ原型中调用broadcast方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM