如何从协议外发送Autobahn/Twisted WAMP消息?

6 投票
1 回答
3292 浏览
提问于 2025-04-17 23:13

我正在按照这个GitHub代码里的基本WAMP发布订阅示例进行学习:

这个示例是在类里面发布消息的:

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)

我想创建一个引用,这样我就可以在代码的其他地方通过这个连接发布消息,也就是说像这样: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)

我在类里面设置的任何引用会附加到哪里呢?是附加到client吗?还是transport_factory?或者session_factory

1 个回答

7

当你的应用会话加入WAMP环境时,它会在应用会话工厂上设置一个指向自己的引用:

class MyAppComponent(ApplicationSession):

   ... snip

   def onJoin(self, details):
      if not self.factory._myAppSession:
         self.factory._myAppSession = self

这样你就可以在代码的其他地方访问这个会话,比如:

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

撰写回答