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.
like this::
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()
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 atry
/except socket.timeout:
around it to catch that case. (Aselect.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!-)