【问题标题】:How to make socket.listen(1) work for some time and then continue rest of code?如何使 socket.listen(1) 工作一段时间然后继续其余代码?
【发布时间】:2011-01-27 12:01:56
【问题描述】:

我正在制作一个创建 tcp 套接字并在端口范围内工作的服务器,每个端口都会在该端口上侦听一段时间,然后继续执行其余代码。

像这样::

import socket

sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

msg =''
ports = [x for x in xrange(4000)]
while True:
    try:
        for i in ports:
            sck.bind(('',i))
            ## sck.listen(1)
            ## make it just for some time and then continue this

            ## if there a connection do this
                conn, addr = sck.accept()
                msg = conn.recv(2048)
                ## do something
            ##if no connection continue the for loop
            conn.close()
    except KeyboardInterrupt:
        exit()

那么我怎样才能让 sck.listen(1) 工作一段时间??

【问题讨论】:

  • listen() 不会阻塞,也不能循环调用。你的意思是accept()

标签: python sockets ports


【解决方案1】:

您可以将套接字上的settimeout 设置为每次您想要等待的最长时间(在每次listen 到您想要等待的时间之前再次调用它这个时间周围)——如果计时器到期,你会得到一个异常socket.timeout,所以一定要在它周围有一个try/except socket.timeout:来捕捉这种情况。 (带有超时的select.select 也可以工作,并且具有能够在多个套接字上等待各种条件的优势,但作为对您非常具体的问题的答案,它有点不直接)。

上次我给出这样的答案时,我得到了很多反对意见......大概是纯粹主义者想要确保没有人以他们不赞成的方式进行程序(例如,通过像你这样的非常特殊的结构,而不是许多正常的,通常的编写服务器的方式)。让我们看看这次会发生什么!-)

【讨论】:

  • 大声笑,我会投票,我会用这个作为临时解决方案,直到我得到另一个好的答案:)..
  • listen() 不会阻塞,也不能循环调用。阻塞的是accept(),如果设置了超时,则会对超时做出反应。你和 OP 犯了同样的错误。
猜你喜欢
  • 2011-01-02
  • 1970-01-01
  • 2016-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 1970-01-01
相关资源
最近更新 更多