How to use TCP Keepalive with endpoints in Twisted?

Twisted supports TCP Keepalive . But I cannot find an easy way to install them on endpoints (client and server).

What is the best practice for this now?

+4
source share
1 answer

I do not see a way in which you can achieve this from endpoints using the API. However, look at the source twisted.internet.endpoints._WrappingProtocol- you could configure the endpoint to use _WrappingFactory*, which causes a delayed callback when the connection is made. At this point, the transport is installed in the protocol, and you can call setTcpKeepAlive.

, , , . .

self.transport.setTcpKeepAlive connectionMade , ( , ).

#!/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()

, , , , , .

* , _WrappingFactory ClientFactory .

+4

All Articles