【问题标题】:How to pass connection success or failure to the caller in the Twisted framework?如何将连接成功或失败传递给 Twisted 框架中的调用者?
【发布时间】:2017-09-30 02:20:49
【问题描述】:

在完成了一些基本的tutorials 之后,我希望我的 TCP/UDP 客户端退出并显示一个指示它是否连接的代码。在 Twisted 中返回退出代码的正确方法是:

point = TCP4ClientEndpoint(reactor, "localhost", 1234)
d = connectProtocol(point, ClientProtocol())
reactor.run()
sys.exit(0)

然后,当进程终止时,它将以代码 0 退出,表示正常终止。如果客户端超时而不是成功连接,它应该如何将一个值传回给那个然后可以传递给 sys.exit 而不是常量 0?

【问题讨论】:

  • 使用函数和return退出代码?

标签: python twisted twisted.internet


【解决方案1】:

通过关注Deferred的结果来判断TCP连接是成功还是失败:

d = connectProtocol(point, ClientProtocol())
d.addCallbacks(
    connected,
    did_not_connect,
)

通过connecteddid_not_connect 的适当实现,您应该能够将合适的值传递给后续的sys.exit 调用。

例如,

class Main(object):
    result = 1

    def connected(self, passthrough):
        self.result = 0
        return passthrough

    def did_not_connect(self, passthrough):
        self.result = 2
        return passthrough

    def exit(self):
        sys.exit(self.result)

main = Main()
d = connectProtocol(point, ClientProtocol())
d.addCallbacks(
    main.connected,
    main.did_not_connect,
)
reactor.run()
main.exit()

【讨论】:

  • 因为我也需要支持 UDP,所以我不能使用回调(AFAICT,listenUDP 不返回 Deferred 实例),所以我不得不采取稍微不同的方法,在道德上是相同的:添加将 twisted.protocols.policies.TimeoutMixin 添加到协议类,在 timeoutConnection() 中设置实例变量,并在 sys.exit() 调用中读取实例变量。不幸的是,这涉及到我希望避免的事情,使用全局实例来传递非__init__ 方法中的状态集,但似乎没有其他方法可以做到这一点。
  • UDP 客户端没有有意义的连接失败。 listenUDP 同步成功。无论如何,我在此答案中概述的相同方法也可用于避免其他地方的全局状态。
猜你喜欢
  • 2014-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-18
相关资源
最近更新 更多