1
votes

Im new to Twisted. Suppose im writing a client which connects over TCP to a server.I would like to know what the difference is between connectionLost defined in Protocol versus clientConnectionLost defined in Factory. For example consider the following echo client which connects to an echo server:

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()

When i terminate the echo server program, both "connectionLost called" and "clientConnectionLost called" gets printed. So what is the difference between the two ?

Thanks

1

1 Answers

3
votes

If you are using connectTCP, these APIs are roughly identical. The main difference is that one ClientFactory may be handling multiple connections.

However, you should not be using connectTCP in your applications; it's a low-level API which, at this point in Twisted's history, is mainly useful for internal implementation mechanisms and not for applications. Instead, adopt the Endpoints API, and if you use IStreamClientEndpoint, you will use only IFactory, not ClientFactory, and therefore there will be no extraneous clientConnectionFailed and clientConnectionLost methods in your code.