【问题标题】:Getting object instances from a Twisted factory (Python) [duplicate]从 Twisted 工厂 (Python) [重复] 获取对象实例
【发布时间】:2012-10-30 00:19:53
【问题描述】:

我正在使用带有以下代码的 autobhan websockets 库:

    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")

该代码可以很好地接收消息,但是我如何访问 EchoServerProtocol 的实例以便随时发送任意消息?

【问题讨论】:

  • 不,不是。我问了这两个问题。该示例中的侦听器不需要您使用工厂。在此示例中,我无法将 WebSocketServerProtocol 的实例存储在变量中。这就是为什么我很困惑。我认为 oberstet 的回答应该足够了
  • 确实是一样的。工厂是一个偶然的细节。每种情况下的底层解决方案都是相同的。

标签: python multithreading networking asynchronous twisted


【解决方案1】:

一种方法是向工厂注册您的协议实例,并通过工厂与您应用的其余部分进行通信。

这是一个例子:

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

在这个例子中,每个协议实例都会在 WebSocket 会话建立后在工厂中注册自己。然后,您可以通过工厂向所有当前连接的协议实例广播消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    相关资源
    最近更新 更多