Twisted 中 connectionLost 和 clientConnectionLost 的区别

Difference between connectionLost and clientConnectionLost in Twisted

我是 Twisted 的新手。假设我正在编写一个通过 TCP 连接到 server.I 的客户端,想知道 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()

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

谢谢

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

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