Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to set a timeout on a socket in Twisted?

I realize I'm probably just dumb and missing something big and important, but I can't figure out how to specify a timeout in twisted using reactor.listenUDP. My goal is to be able to specify a timeout, and after said amount of time, if DatagramProtocol.datagramReceived has not been executed, have it execute a callback or something that I can use to call reactor.stop(). Any help or advice is appreciated. Thanks

like image 429
Jurassic_C Avatar asked Oct 21 '08 12:10

Jurassic_C


2 Answers

I think reactor.callLater would work better than LoopingCall. Something like this:

class Protocol(DatagramProtocol):
    def __init__(self, timeout):
        self.timeout = timeout

    def datagramReceived(self, datagram):
        self.timeout.cancel()
        # ...

timeout = reactor.callLater(5, timedOut)
reactor.listenUDP(Protocol(timeout))
like image 177
daf Avatar answered Sep 21 '22 04:09

daf


Since Twisted is event driven, you don't need a timeout per se. You simply need to set a state variable (like datagramRecieved) when you receive a datagram and register a looping call that checks the state variable, stops the reactor if appropriate then clears state variable:

from twisted.internet import task
from twisted.internet import reactor

datagramRecieved = False
timeout = 1.0 # One second

# UDP code here

def testTimeout():
    global datagramRecieved
    if not datagramRecieved:
        reactor.stop()
    datagramRecieved = False


l = task.LoopingCall(testTimeout)
l.start(timeout) # call every second

# l.stop() will stop the looping calls
reactor.run()
like image 26
Aaron Maenpaa Avatar answered Sep 18 '22 04:09

Aaron Maenpaa