Jur*_*c_C 8 python sockets networking twisted
我意识到我可能只是愚蠢而且缺少一些重要的东西,但我无法弄清楚如何使用reactor.listenUDP来指定扭曲的超时.我的目标是能够指定超时,并且在所述时间之后,如果DatagramProtocol.datagramReceived尚未执行,请让它执行回调或我可以用来调用reactor.stop()的东西.任何帮助或建议表示赞赏.谢谢
daf*_*daf 13
我认为reactor.callLater会更好LoopingCall.像这样的东西:
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))
Run Code Online (Sandbox Code Playgroud)
由于Twisted是事件驱动的,因此您本身不需要超时.您只需在接收数据报时设置状态变量(如datagramRecieved)并注册检查状态变量的循环调用,如果合适则停止反应器然后清除状态变量:
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()
Run Code Online (Sandbox Code Playgroud)