【发布时间】: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()?