Search code examples
pythonmultithreadingnetwork-programmingasynchronoustwisted

Getting object instances from a Twisted factory (Python)


I am using the autobhan websockets library with the following code:

    from twisted.internet import reactor
    from autobahn.websocket import WebSocketServerFactory, \
                                   WebSocketServerProtocol, \
                                   listenWS


    class EchoServerProtocol(WebSocketServerProtocol):

       def onMessage(self, msg, binary):
          self.sendMessage(msg, binary)

       def sendRandomMessage(message):
          self.sendMessage(message,true)


    if __name__ == '__main__':

       factory = WebSocketServerFactory("ws://192.168.1.135:9999", debug = False)
       factory.protocol = EchoServerProtocol
       listenWS(factory)
       reactor.run()

       #insert random code here.  Things happen independent of the connection state.
       #somehow access EchoServerProtocolINSTANCE.sendMessage("MESSAGE_HERE")

The code works well for receiving messages, but how can I access the instance of EchoServerProtocol in order to send arbitrary messages at any time?


Solution

  • One way is to register your protocol instance with the factory, and communicate via the factory from the rest of your app.

    Here is an example:

    https://github.com/tavendo/AutobahnPython/blob/master/examples/websocket/broadcast/server.py#L34

    With this example, every protocol instance registers itself on the factory after the WebSocket session has been established. You can then broadcast messages to all currently connected protocol instances via the factory.