我是 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
,因此不会有多余的 clientConnectionFailed
和 clientConnectionLost
方法你的代码。
关于python - Twisted 中connectionLost 和clientConnectionLost 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32439371/