【问题标题】:Difference between connectionLost and clientConnectionLost in TwistedTwisted 中 connectionLost 和 clientConnectionLost 的区别
【发布时间】:2015-09-07 21:43:56
【问题描述】:

我是 Twisted 的新手。假设我正在编写一个通过 TCP 连接到服务器的客户端。我想知道 Protocol 中定义的 connectionLost 与 Factory 中定义的 clientConnectionLost 之间有什么区别。例如,考虑以下连接到回显服务器的回显客户端:

from twisted.internet import reactor, protocol

class EchoClient(protocol.Protocol):
    def connectionMade(self):
        self.transport.write("Hello, World!")

    def connectionLost(self,reason):
        print "connectionLost called "

    def dataReceived(self,data):
        print "Server said: ", data

class EchoFactory(protocol.ClientFactory):
    def buildProtocol(self, addr):
        return EchoClient()

    def clientConnectionFailed(self, connector, reason):
        print "Connection failed"
        reactor.stop()

    def clientConnectionLost(self, connector, reason):
        print "clientConnectionLost called"
        reactor.stop()


reactor.connectTCP("localhost",8000,EchoFactory())
reactor.run()

当我终止回显服务器程序时,“connectionLost called”和“clientConnectionLost called”都会被打印出来。那么这两者有什么区别呢?

谢谢

【问题讨论】:

    标签: python twisted


    【解决方案1】:

    如果您使用的是connectTCP,则这些 API 大致相同。主要区别在于一个ClientFactory 可能处理多个连接。

    但是,您不应该在您的应用程序中使用connectTCP;它是一个低级 API,在 Twisted 的历史上,它主要用于内部实现机制而不是应用程序。相反,采用Endpoints API,如果你使用IStreamClientEndpoint,你将只使用IFactory,而不是ClientFactory,因此你的代码中不会有多余的clientConnectionFailedclientConnectionLost方法。

    【讨论】:

    • 非常感谢 Glyph,我现在明白了。得到项目创建者本人的回复感觉真好:)
    猜你喜欢
    • 2018-05-04
    • 2011-02-01
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多