如何在 Twisted 中将 TCP Keepalive 与端点一起使用?

Elr*_*ond 5 python tcp twisted

Twisted 确实支持TCP Keepalive。但是我找不到在端点(客户端和服务器)上设置这些的简单方法。

这样做的最佳当前做法是什么?

Pet*_*son 4

我看不出有什么方法可以通过 API 从端点干净地实现这一点。但是,请查看源代码twisted.internet.endpoints._WrappingProtocol- 您可以将端点设置为使用_WrappingFactory* ,它会在建立连接时回调延迟。此时,协议上的传输已设置完毕,您可以调用setTcpKeepAlive.

鉴于类名中的下划线,我想说这些是在内部使用的,我不会依赖它们的接口在版本之间保持一致。您应该使用它们作为指南。

或者,只需调用self.transport.setTcpKeepAliveconnectionMade的协议并处理不支持该协议的情况(即通过其他传输使用该协议的情况)。

#!/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()
Run Code Online (Sandbox Code Playgroud)

对于这个简单的示例,我认为这提供了一个相当干净的解决方案,但是在某些情况下可能需要额外的包装器代码。

* 请注意,_WrappingFactory子类ClientFactory和 可能不适合服务器。