python - 如何从协议(protocol)外部发送 Autobahn/Twisted WAMP 消息?

标签 python twisted autobahn wamp-protocol

我正在关注 the github code 中的基本 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)

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

来自这个类似的question答案似乎是在连接时,我需要设置类似 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)

我在类里面设置的任何引用资料会附加到哪里?到客户端?到 transport_factory?到 session_factory?

最佳答案

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

class MyAppComponent(ApplicationSession):

   ... snip

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

然后您可以从代码中的其他地方访问此 session ,例如

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

关于python - 如何从协议(protocol)外部发送 Autobahn/Twisted WAMP 消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22549370/

相关文章:

python - 寻找有关神经网络的良好引用

python - Twisted 和 p2p 应用程序

python - 如何在twisted portforward代理中添加SSL功能

python - twistd.py 记录到标准输出和文件

python - Websocket与高速公路的连接和python中的twisted

Python,将字符串分成几个子串

python - 我正在用 python 编程,但我一直在制作二进制文件

python - 使用 BeautifulSoup 解析 html 表格

Python - 在单独的子进程或线程中运行 Autobahn|Python asyncio websocket 服务器

python-2.7 - 无法收听错误 : Couldn't listen on any:9008: [Errno 98] Address already in use