python - How to send Autobahn/Twisted WAMP message from outside of protocol? -
i following basic wamp pubsub examples in the github code:
this example publishes messages within class:
class component(applicationsession): """ application component publishes event every second. """ def __init__(self, realm = "realm1"): applicationsession.__init__(self) self._realm = realm def onconnect(self): self.join(self._realm) @inlinecallbacks def onjoin(self, details): counter = 0 while true: self.publish('com.myapp.topic1', counter) counter += 1 yield sleep(1)
i want create reference can publish messages on connection elsewhere in code, i.e. myobject.myconnection.publish('com.myapp.topic1', 'my message')
from similar question answer seems upon connection, need set self.factory.myconnection = self
. have tried multiple permutations of without success.
the factory setup portion below:
## create wamp application session factory ## autobahn.twisted.wamp import applicationsessionfactory session_factory = applicationsessionfactory() ## .. , set session class on factory ## session_factory.session = component ## create wamp-over-websocket transport client factory ## autobahn.twisted.websocket import wampwebsocketclientfactory transport_factory = wampwebsocketclientfactory(session_factory, args.wsurl, debug = args.debug) transport_factory.setprotocoloptions(failbydrop = false) ## start websocket client endpoint ## client = clientfromstring(reactor, args.websocket) client.connect(transport_factory)
where reference set within class attached? client
? transport_factory
? session_factory
?
upon app session joining wamp realm, sets reference on app session factory:
class myappcomponent(applicationsession): ... snip def onjoin(self, details): if not self.factory._myappsession: self.factory._myappsession = self
you can access session elsewhere in code, e.g.
@inlinecallbacks def pub(): counter = 0 while true: ## here can access app session created .. ## if session_factory._myappsession: session_factory._myappsession.publish('com.myapp.topic123', counter) print("published event", counter) else: print("no session") counter += 1 yield sleep(1) pub()
Comments
Post a Comment