简体   繁体   中英

How do you share state between protocols in Twisted?

I have two protocols, one a WebSocket server the other a ZeroMQ pull socket. I want to forward things received my ZMQ to the 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 . The latter then has a broadcast method to dispatch an event on all currently connected clients.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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