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()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With