【发布时间】:2014-01-14 13:40:51
【问题描述】:
Twisted 确实支持TCP Keepalive。但我找不到在端点(客户端和服务器)上设置它们的简单方法。
目前最好的做法是什么?
【问题讨论】:
Twisted 确实支持TCP Keepalive。但我找不到在端点(客户端和服务器)上设置它们的简单方法。
目前最好的做法是什么?
【问题讨论】:
我看不出有一种方法可以通过 API 从端点干净地实现这一点。但是,请查看twisted.internet.endpoints._WrappingProtocol 的源代码 - 您可以将端点设置为使用_WrappingFactory*,它会在建立连接时回调延迟。此时在协议上设置了传输,您可以调用setTcpKeepAlive。
鉴于类名中的下划线,我会说这些是在内部使用的,我不会依赖它们的接口在版本之间保持一致。您应该将它们用作指南。
或者,只需在您的协议的connectionMade 中调用self.transport.setTcpKeepAlive 并处理不支持此功能的情况(即该协议用于其他传输的情况)。
#!/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 的子类,可能不适用于服务器。
【讨论】:
twisted.internet.endpoints._WrappingProtocol 的来源 - 您可以将端点设置为使用_WrappingFactory,它在建立连接时回调延迟。此时在协议上设置了传输,您可以调用setTcpKeepAlive。否则,只需将 setTcpKeepAlive 包装在 try except 块中...