Search code examples
pythonsocketspython-3.xtwistedtwisted.internet

Python - Twisted client - check protocol.transport connection in ping loop


I'm creating TCP client socket with Twisted. I need to check connection status in a loop interval in connectionMade method.

from twisted.internet import reactor, protocol

class ClientProtocol(protocol.Protocol):
    def connectionMade(self):
       while not thread_obj.stopped.wait(10):
            print ('ping')
            self.transport.write(b'test') # Byte value

For check connection losing, i manually disconnect my network And I checked some variables after that as bellow:

print (self.connected)
print (self.transport.connector.state)
print (self.transport.connected)
print (self.transport.reactor.running)
print (self.transport.socket._closed)
print (self.factory.protocol.connected)
print (self._writeDissconnected)

But any variables value didn't change after disconnecting my network :(

My question is: which variables will be set when the connection lost? I mean how can i check the connection status and if it's disconnect, how can i reconnect that?


Solution

  • override connectionLost method to catch disconnection. to official docs

    Edit about reconnection: Reconnection mostly is a logical decision. You may want to add logic between 'connectionLost' and 'reconnect'.

    Anyway, You can use ReconnectingClientFactory for better code. ps: using factory pattern at reconnection is best way to keep code clean and smart.

    class MyEchoClient(Protocol):
        def dataReceived(self, data):
            someFuncProcessingData(data)
            self.transport.write(b'test')
    
    class MyEchoClientFactory(ReconnectingClientFactory):
        def buildProtocol(self, addr):
            print 'Connected.'
            return MyEchoClient()
    
        def clientConnectionLost(self, connector, reason):
            print 'Lost connection.  Reason:', reason
            ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
    
        def clientConnectionFailed(self, connector, reason):
            print 'Connection failed. Reason:', reason
            ReconnectingClientFactory.clientConnectionFailed(self, connector,
                                                         reason)