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()
How to use TCP Keepalive with Endpoints in Twisted?