是否可以在Twisted中设置套接字超时?

时间:2008-10-21 12:56:33

标签: python networking sockets twisted

我意识到我可能只是愚蠢而且缺少一些重要的东西,但是我无法弄清楚如何使用reactor.listenUDP指定扭曲的超时。我的目标是能够指定超时,并且在所述时间之后,如果DatagramProtocol.datagramReceived尚未执行,请让它执行回调或我可以用来调用reactor.stop()的东西。任何帮助或建议表示赞赏。感谢

4 个答案:

答案 0 :(得分:13)

我认为reactor.callLaterLoopingCall效果更好。像这样:

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))

答案 1 :(得分:5)

由于Twisted是事件驱动的,因此您本身不需要超时。您只需在收到数据报时设置状态变量(如datagramRecieved)并注册检查状态变量的looping call,如果合适则停止反应器然后清除状态变量:

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()

答案 2 :(得分:3)

使用reactor我们必须使用callLater。 在connectionMade时启动超时倒计时。 lineReceived时重置超时倒计时。

这是

# -*- coding: utf-8 -*-

from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor, defer

_timeout = 27


class ServiceProtocol(LineReceiver):

    def __init__(self, users):
        self.users = users


    def connectionLost(self, reason):
        if self.users.has_key(self.name):
            del self.users[self.name]

    def timeOut(self):
        if self.users.has_key(self.name):
            del self.users[self.name]
        self.sendLine("\nOUT: 9 - Disconnected, reason: %s" % 'Connection Timed out')
        print "%s - Client disconnected: %s. Reason: %s" % (datetime.now(), self.client_ip, 'Connection Timed out' )
        self.transport.loseConnection()

    def connectionMade(self):
        self.timeout = reactor.callLater(_timeout, self.timeOut)

        self.sendLine("\nOUT: 7 - Welcome to CAED")

    def lineReceived(self, line):
        # a simple timeout procrastination
        self.timeout.reset(_timeout)

class ServFactory(Factory):

    def __init__(self):
        self.users = {} # maps user names to Chat instances

    def buildProtocol(self, addr):
        return ServiceProtocol(self.users)

port = 8123
reactor.listenTCP(port, ServFactory())
print "Started service at port %d\n" % port
reactor.run()

答案 3 :(得分:0)

更好的方法是使用twisted.protocols.policies.TimeoutMixin。它基本上是callLater但是被抽象为Mixin