欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python连接池实现示例程序

程序员文章站 2022-09-09 08:24:54
复制代码 代码如下:import socketimport queueimport threading def worker():    w...

复制代码 代码如下:

import socket
import queue
import 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()