How to make socket.listen(1) work for some time and then continue rest of code?

自古美人都是妖i 提交于 2019-12-03 21:27:02

问题


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 ??


回答1:


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!-)



来源:https://stackoverflow.com/questions/2444178/how-to-make-socket-listen1-work-for-some-time-and-then-continue-rest-of-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!