如果n秒后没有读取,则Twisted TCP服务器超时

时间:2014-03-19 06:24:37

标签: twisted

通过以下示例,如何在读取时最好地实现看门狗定时器?

如果没有收到数据,我希望服务器在n秒后关闭连接。然后,客户端必须重新连接才能继续发送数据。

from twisted.internet import reactor, protocol as p
from threading import Lock

class Echo(p.Protocol):
    def __init__(self, factory):
        self.factory = factory

    def connectionMade(self):
        with self.factory.mutex:
            self.factory.clients.append(self)

    def connectionLost(self, reason):
        print('Connection lost)
        with self.factory.mutex:
            self.factory.clients.remove(self)

    def dataReceived(self, data):
        self.transport.write(data)

class EchoFactory(p.Factory):
    def __init__(self):
        self.clients = []
        self.mutex = Lock()


    def buildProtocol(self, addr):
        print 'Connection by', addr
        return Echo(self)

reactor.listenTCP(5007, EchoFactory())
reactor.run()

2 个答案:

答案 0 :(得分:13)

这种模式的Twisted中有一个帮助,twisted.protocols.policies.TimeoutMixin

from twisted.protocols.policies import TimeoutMixin
from twisted.internet.protocol import Protocol

class YourProtocol(Protocol, TimeoutMixin):
    def connectionMade(self):
        self.setTimeout(N)

    def dataReceived(self, data):
        self.resetTimeout()

    def timeoutConnection(self):
        self.transport.abortConnection()

答案 1 :(得分:0)

这样的事情:

class Echo(p.Protocol):
    def connectionMade(self):
        self._gotdata = True
        def check():
           if self._gotdata:
              self._gotdata = False
              reactor.callLater(10, check)
           else:
              self.transport.abortConnection()
        check()

        with self.factory.mutex:
            self.factory.clients.append(self)

    def dataReceived(self, data):
        self._gotdata = True
        self.transport.write(data)