Frage

With the following example, how can I best implement a watchdog timer on reads?

I want the server to close a connection after n seconds if no data is received from it. The client will then have to reconnect in order to continue to send data.

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()
War es hilfreich?

Lösung

There's a helper in Twisted for this pattern, 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()

Andere Tipps

Something like this:

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)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top