How to use TCP Keepalive with Endpoints in Twisted?

此生再无相见时 提交于 2019-12-12 11:33:53

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/20792636/how-to-use-tcp-keepalive-with-endpoints-in-twisted

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!