【问题标题】:Using DeferredQueue for inter-task communication in Twisted在 Twisted 中使用 DeferredQueue 进行任务间通信
【发布时间】:2013-09-27 15:02:18
【问题描述】:

我的客户目前正在执行以下操作:

  1. 连接
  2. 在本地收集一些数据
  3. 将该数据发送到服务器
  4. 重复
  5. 如果断开连接,则重新连接并继续上述操作(未显示)

像这样:

def do_send(self):
    def get_data():
        # do something
        return data

    def send_data(data)
        self.sendMessage(data)

    return deferToThread(get_data).addCallback(send_data)

def connectionMade(self):
    WebSocketClientProtocol.connectionMade(self)
    self.sender = task.LoopingCall(self.do_send)
    self.sender.start(60)

但是,当断开连接时,我希望继续收集数据,可能会排队并以一定的限制写入文件。我已经查看了似乎是我需要的 DeferredQueue 对象,但我似乎无法破解它。

在伪代码中,它会是这样的:

queue = DeferredQueue

# in a separate class from the client protocol
def start_data_collection():
    self.collecter = task.LoopingCall(self.get_data)
    self.sender.start(60)

def get_data()
    # do something
    queue.put(data)

然后让客户端协议检查队列,这是我迷路的地方。 DeferredQueue 是我需要的,还是有更好的方法?

【问题讨论】:

    标签: python asynchronous twisted deferred


    【解决方案1】:

    列表也可以。您可能会迷失在同一个地方 - 您如何让客户端协议检查列表?

    不管怎样,这里有一个答案:

    queued = []
    
    ...
    
    connecting = endpoint.connect(factory)
    def connected(protocol):
        if queued:
            sending = protocol.sendMessage(queued.pop(0))
            sending.addCallback(sendNextMessage, protocol)
            sending.addErrback(reconnect)
    connecting.addCallback(connected)
    

    这里的想法是,在某个时候会发生一个事件:您的连接已建立。此示例将该事件表示为 connecting Deferred。当事件发生时,connected 被调用。此示例从队列中弹出第一项(list)并将其发送。它等待发送被确认,然后发送下一条消息。它还暗示了一些关于通过重新连接来处理错误的逻辑。

    您的代码可能看起来不同。您可以使用 Protocol.connectionMade 回调来表示连接事件。核心思想是相同的——定义回调以在某些事件发生时对其进行处理。是使用端点的 connect Deferred 还是协议的 connectionMade 并不重要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-08
      • 1970-01-01
      相关资源
      最近更新 更多