python - Twisted 中connectionLost 和clientConnectionLost 之间的区别

标签 python twisted

我是 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”都会被打印。那么两者有什么区别呢?

谢谢

最佳答案

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

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

关于python - Twisted 中connectionLost 和clientConnectionLost 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32439371/

相关文章:

python - Mac 上的 pip install 和 sudo

python - matplotlib 的自定义箭头样式,pyplot.annotate

python - 带有 TLS 的 Twisted Python ESMTP 邮件服务器/转储

python - 在客户端断开连接后,如何使twistedmatrix子进程继续处理?

python - WebSocket 在 1000 条消息后关闭

python - Twisted 中不同的协议(protocol)如何相互交互

python - 在 python 中将文件路径作为命令行参数传递

python - 使用正则表达式在地址中查找电子邮件域

python - Odoo模块开发错误: AssertionError: Element openerp has extra content: data

python扭曲的多线程服务器