如何使socket.listen(1)工作一段时间,然后继续执行其余代码? [英] How to make socket.listen(1) work for some time and then continue rest of code?
问题描述
我正在制造一个制造TCP套接字并在端口范围内工作的服务器,每个端口将在该端口上侦听一段时间,然后继续其余代码.
I'm making server that make a tcp socket and work over port range, with each port it will listen on that port for some time, then continue the rest of the code.
像这样::
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)工作一段时间?
so how i could make sck.listen(1) work just for some time ??
推荐答案
You can settimeout on the socket to the maximum amount of time you want to wait on it each time (call it again before every listen
to the time you want to wait this time around) -- you'll get an exception, socket.timeout, if the timer expires, so be sure to have a try
/except socket.timeout:
around it to catch that case. (A select.select
with a timeout would also work, and has the advantage of being able to wait on multiple sockets and for various conditions, but it's a bit less direct as an answer to your very specific question).
上次我给出这样的答案时,我有很多反对意见……大概是纯粹主义者,他们想要确保没有人曾经反对过他们反对的程序(例如,通过像您这样的非常特殊的结构而不是许多人)正常的,通常的服务器编写方式).让我们看看这次发生了什么!-)
I got many downvotes last time I gave such an answer... presumably by purists who want to make sure nobody, ever, programs in way they disapprove of (e.g. through a very peculiar construct such as yours as opposed to the many normal, usual way of writing servers). Let's see what happens this time around!-)
这篇关于如何使socket.listen(1)工作一段时间,然后继续执行其余代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!