class EchoProtocol(protocol.Protocol):

    def connectionMade(self):
        print('Client Connected Detected!')
try:
    self.transport.setTcpKeepAlive(1)
except AttributeError:
    pass

def connectionLost(self, reason):
    print('Client Connection Lost!')

def dataReceived(self, data):
    self.transport.write(data)
factory = protocol.Factory()
factory.protocol = EchoProtocol
reactor.listenTCP(8000, factory)
reactor.run()
How to use TCP Keepalive with Endpoints in Twisted?