如何在 Twisted 中将 TCP Keepalive 与端点一起使用? [英] How to use TCP Keepalive with Endpoints in Twisted?

查看:34
本文介绍了如何在 Twisted 中将 TCP Keepalive 与端点一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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.

或者,只需在您的协议的 connectionMade 中调用 self.transport.setTcpKeepAlive 并处理不支持的情况(即该协议用于其他传输).

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.

* 请注意,_WrappingFactoryClientFactory 的子类,可能不适用于服务器.

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

这篇关于如何在 Twisted 中将 TCP Keepalive 与端点一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆