python连接池实现示例程序

代码如下:

import socketimport queueimport threading

def worker(): while true: i = q.get() conn=i[0] addr=i[1] while 1: sms=conn.recv(1024) if sms!=””: print “message from (“+str(addr[0])+”:”+str(addr[1])+”): “+sms else: print “close the connection from (“+str(addr[0])+”:”+str(addr[1])+”)” conn.close() break q.task_done()if __name__==”__main__”: q = queue.queue() thread_num=5000 s=socket.socket(socket.af_inet,socket.sock_stream) s.setsockopt(socket.sol_socket,socket.so_reuseaddr,1) s.bind((“”,4242)) s.listen(50000) print “server is listening at 4242” for _ in range(0,thread_num): t=threading.thread(target=worker) t.setdaemon(1) t.start() while 1: conn,addr=s.accept() print “connection come from (“+str(addr[0])+”:”+str(addr[1])+”)” q.put((conn,addr)) q.join()