如何从协议外发送高速公路/扭曲的WAMP消息?

haz*_*zey 6 python twisted autobahn wamp-protocol

我正在遵循github代码中的基本wamp pubsub示例:

此示例从类中发布消息:

class Component(ApplicationSession):
   """
An application component that publishes an 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)
Run Code Online (Sandbox Code Playgroud)

我想创建一个引用,以便我可以从代码中的其他地方通过此连接发布消息,即 myobject.myconnection.publish('com.myapp.topic1', 'My message')

从这个类似的问题来看,答案似乎是在连接时,我需要设置类似的东西self.factory.myconnection = self.我已经尝试了多次这种排列而没有成功.

出厂设置部分如下:

   ## create a WAMP application session factory
   ##
   from autobahn.twisted.wamp import ApplicationSessionFactory
   session_factory = ApplicationSessionFactory()


   ## .. and set the session class on the factory
   ##
   session_factory.session = Component


   ## create a WAMP-over-WebSocket transport client factory
   ##
   from autobahn.twisted.websocket import WampWebSocketClientFactory
   transport_factory = WampWebSocketClientFactory(session_factory, args.wsurl, debug = args.debug)
   transport_factory.setProtocolOptions(failByDrop = False)


   ## start a WebSocket client from an endpoint
   ##
   client = clientFromString(reactor, args.websocket)
   client.connect(transport_factory)
Run Code Online (Sandbox Code Playgroud)

我在课堂上设置的任何参考文献都附在哪里?到client?到transport_factory?到session_factory

obe*_*tet 7

在您的应用会话加入WAMP领域后,它会在应用会话工厂中设置自己的引用:

class MyAppComponent(ApplicationSession):

   ... snip

   def onJoin(self, details):
      if not self.factory._myAppSession:
         self.factory._myAppSession = self
Run Code Online (Sandbox Code Playgroud)

然后,您可以从代码中的其他位置访问此会话,例如

   @inlineCallbacks
   def pub():
      counter = 0  
      while True:
         ## here we can access the app session that was 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()
Run Code Online (Sandbox Code Playgroud)