如何在select中正确使用timeout参数?

时间:2013-03-04 05:31:44

标签: python sockets timeout

我是套接字编程的新手(有点像Python),我无法按照我想要的方式(在服务器端)使用select超时。在客户端连接之前,超时工作正常。我给它一个1秒的值,超时每1秒在我的循环中到期。

然而,一旦客户端连接,它不会等待1秒钟告诉我超时到期。它只是尽可能快地循环并告诉我超时到期。这是我的代码片段:

while running:
    try:
        self.timeout_expired = False
        inputready, outputready, exceptready = select.select(self.inputs, self.outputs, [], self.timeout)
    except select.error, e:
        break
    except socket.error, e:
        break

    if not (inputready):
        # Timeout expired
        print 'Timeout expired'
        self.timeout_expired = True

    # Additional processing follows here

我不确定这个代码是否足以查看我的问题所在,所以如果您需要了解更多内容,请与我们联系。基本上,在客户端连接之后,它至少出现它忽略1秒的超时并且尽可能快地运行,不断告诉我“Timeout expired”。知道我错过了什么吗?

非常感谢!!

编辑:我应该澄清......“inputready”表示连接或向服务器发送数据的客户端的输入,以及来自服务器的stdin。 select中返回的其他变量只是服务器端变量,我正在尝试检测CLIENT是否花了太长时间才能回复,所以我只检查inputready是否为空。

2 个答案:

答案 0 :(得分:2)

如果inputreadyoutputreadyexceptready全部为空,则只会暂停。我猜您已将客户端套接字添加到self.inputsself.outputs。由于输出套接字通常是可写的,因此它将始终显示在outputready中。如果您准备输出内容,请仅将客户端套接字添加到self.outputs

答案 1 :(得分:0)

“当超时到期时,select()返回三个空列表。 ...要使用超时,需要在select()调用中添加额外的参数,并在select()返回后处理空列表。”

readable, writable, exceptional = select.select(inputs, outputs, inputs,timeout)

if not (readable or writable or exceptional):
    print('  timed out, do some other work here', file=sys.stderr)

[https://pymotw.com/3/select/index.html][1]