Search code examples
pythontcptwisted

How to use TCP Keepalive with Endpoints in Twisted?


Twisted does support TCP Keepalive. But I can't find a simple way to set those on endpoints (client and server).

What is the best current practice for doing this?


Solution

  • I can't see a way that you can achieve this from endpoints cleanly via the API. However take a look at the source to twisted.internet.endpoints._WrappingProtocol - you could possibly set your endpoint to use a _WrappingFactory* which callbacks a deferred when the connection is made. At this point transport is set on the protocol and you can call setTcpKeepAlive.

    Given the underscore in the class name, I would say these are meant to be used internally and I wouldn't depend on their interface being consistent between releases. You should use them as a guide.

    Alternatively, just call self.transport.setTcpKeepAlive in connectionMade of your Protocol and handle the case where this is not supported (i.e. where the protocol is used over another transport).

    #!/usr/bin/python
    # based on example at http://twistedmatrix.com/pipermail/twisted-python/2008-June/017836.html
    from twisted.internet import protocol 
    from twisted.internet import reactor
    
    class EchoProtocol(protocol.Protocol):
        def connectionMade(self):
            print "Client Connected Detected!"
            ### enable keepalive if supported
            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()
    

    For this simple example I feel that this gives a fairly clean solution, however there are probably situations where the additional wrapper code is warranted.

    * Note that _WrappingFactory subclasses ClientFactory and may not be suitable for servers.