当没有更多的连接asyncore.loop不会终止(asyncore.loop doesn'

2019-11-01 11:28发布

我下面一些示例代码中使用asyncore 这里 ,仅在已经设置了timeout的值asyncore.loop如下面的完整的例子:

import smtpd
import asyncore

class CustomSMTPServer(smtpd.SMTPServer):

    def process_message(self, peer, mailfrom, rcpttos, data):
        print 'Receiving message from:', peer
        print 'Message addressed from:', mailfrom
        print 'Message addressed to  :', rcpttos
        print 'Message length        :', len(data)
        return

server = CustomSMTPServer(('127.0.0.1', 1025), None)

asyncore.loop(timeout = 1)

我曾预计,超时1秒后发生,但这种情况并非如此。 该代码会运行超过一秒钟更长的时间。 我缺少的是在这里吗?

Answer 1:

timeout参数asyncore.loop()是时间的量select.select呼叫等待数据。 如果没有数据之前timeout用完它会循环,并呼吁select.select一次。

同为channels的想法。 这并不意味着开放套接字而是指活跃asyncore.dispatcherasynchat.async_chat实例。 如果要停止循环,你将不得不调用close()上注册的所有实例方法。

在你的情况server.close()将关闭实例/通道和从删除asyncore循环。 如果没有更多的渠道是活动这个循环将终止运行本身。



Answer 2:

我真的不知道,如果timeout参数asyncore.loop()真的是为了超时函数调用asyncore.loop()在指定时间后,但这里是一个收据,以使该功能超时在指定时间后(更换与线asyncore.loop()中的示例代码):

import signal

class TimeoutError(Exception): pass

# define the timeout handler
def handler(signum, frame):
    raise TimeoutError()

# set the timeout handler and the signal duration
signal.signal(signal.SIGALRM, handler)
signal.alarm(1)
try:
    asyncore.loop()
except TimeoutError as exc:
    print "timeout"
finally:
    signal.alarm(0)


Answer 3:

asyncore.loop的超时()可以选择超时()。

这是没有用的,因为当选择()超时,它循环回来,看到的伪代码:

while True:
    do_something()
    select(...)
    do_something_else()

如果我做模拟与防火墙-ED插座,在我的Python 2.7.3 asyncore.loop()超时1分钟后没有数据从一些插座接收。

我发现非常有用的按照asyncore.dispatcher“子”的方法:

def handle_error(self):
    raise

这样,我有“正确”的异常转储。

因为我不希望有异常,后来我改成了类似:

def handle_error(self):
    print "Error downloading %s" % self.host
    pass

现在我的代码工作正确的,无一例外。

我没有找到一个方法来控制超时。



文章来源: asyncore.loop doesn't terminate when there are no more connections