#A optional parameter for select is TIMEOUT timeout = 10
while inputs: print "waiting for next event" #-------------------------------------------------- readable , writable , exceptional = select.select(inputs, outputs, inputs) #-------------------------------------------------- for temp in readable: print temp print "writable:",writable print "exceptional",exceptional
# When timeout reached , select return three empty lists if not (readable or writable or exceptional) : print "Time out ! " break; for s in readable : if s is server: # A "readable" socket is ready to accept a connection connection, client_address = s.accept() print " connection from ", client_address connection.setblocking(0) inputs.append(connection) message_queues[connection] = Queue.Queue() ...........................略 ```
创建十个 socket 用于连接服务器
```python import socket
messages = ["This is the message" , "It will be sent" , "in parts "]
print "Connect to the server"
server_address = ("localhost",10001)
#Create a TCP/IP sock
socks = []
for i in range(10): socks.append(socket.socket(socket.AF_INET,socket.SOCK_STREAM))
for s in socks: s.connect(server_address)
counter = 0 for message in messages : #Sending message from different sockets for s in socks: counter+=1 print " %s sending %s" % (s.getpeername(),message+" version "+str(counter)) s.send(message+" version "+str(counter)) #Read responses on both sockets for s in socks: data = s.recv(1024) print " %s received %s" % (s.getpeername(),data) if not data: print "closing socket ",s.getpeername() s.close() ```
好的,其实我也是看过类似的文档。但是,可能我没看到,或者说不能完全理解(毕竟 English 不是很好 。。。。)刚才也是读了这个文档,在这个官方文档中还是没有提到 select 函数在 timeout 不填的时候返回时,是等到全部的 socket 连接入,还是只要有一个 socket 连入就返回。下面这两句应该是指 timeout 有值和 timeout 为 0 时的情况??还是说为 0 的情况和不填的情况是一样的? When the timeout argument is omitted the function blocks until at least one file descriptor is ready.A time-out value of zero specifies a poll and never blocks.