select 多并发socket 例子
import select
import socket
import Queue
listen_addr=('0.0.0.0',8000)
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
server.bind(listen_addr)
server.setblocking(0)
except socket.error as e:
print e
exit(0)
server.listen(500)
print("starting up on %s port %s"%listen_addr)
inputs=[server,]
outputs=[]
message_queue={}
while True:
print("waiting for next event...")
readable,writeable,exceptionl=select.select(inputs,outputs,inputs)
"可以recv 可以send exception"
for s in readable:
"处理新的客户端连接,并统一接受他们的数据"
if s is server:
client,addr=s.accept()
print("new connection from",addr)
client.setblocking(0)
"""有客户端连接进来就把这个连接先放在select列表中,
现在这些列表中的连接都会交给select去监听,如果列表中有一个客户端发来数据
那么这个客户端所连接的对应fd就会转变成就绪状态,select就会将这个就绪状态的连接
返回给用户程序的(即readable中)
最后循环这个readable列表,取出这个连接,并只接受这些数据暂时存放
"""
inputs.append(client)
message_queue[client]=Queue.Queue()
else:
data=s.recv(1024)
if data:
print("receive come from %s",s.getpeername()[0],data)
message_queue[s].put(data)
if s not in outputs:
outputs.append(s)
else:
print("client connection break")
if s in outputs:
outputs.remove(s)
inputs.remove(s)
del message_queue[s]
for s in writeable:
try:
next_msg=message_queue[s].get_nowait()
except Queue.Empty:
print("client [%s] ")%(s.getpeername()[0]),
print("queue is empty")
outputs.remove(s)
else:
print("sending msg to [%s]"%(s.getpeername()[0]),next_msg)
s.send(next_msg.upper())
for s in exceptionl:
print("handling exception for",s.getpeername())
inputs.remove(s)
if s in outputs:
outputs.remove(s)
s.close()
del message_queue[s]