gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:06:58 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com