Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twisted TCP server timeout if no read after n seconds

Tags:

twisted

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()
like image 283
RoyHB Avatar asked Dec 09 '22 08:12

RoyHB


1 Answers

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()
like image 64
Jean-Paul Calderone Avatar answered Feb 23 '23 12:02

Jean-Paul Calderone