本例通过利用类Queue建立了一个存放着Thread对象的“容器对象”,当Client端申请与Server端通信时,在Server端的“链接循环”中每次拿出一个Thread对象去创建“线程链接”,从而实现了多个客户端同时与服务器端通信的效果,代码如下:
# -*- coding: utf-8 -*- # -*- Author: WangHW -*- import socket from threading import Thread import mythread def Communication(conn): # 通信循环 while 1: try: data = conn.recv(1024) if not data: break print('Client Data:', data.decode('utf-8')) conn.send(data.upper()) except ConnectionResetError: break def Server(ip,post): whw_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) whw_server.bind((ip,post)) whw_server.listen(5) # 链接循环 while 1: conn, addr = whw_server.accept() t = pool.get_thread() #使用线程对象创建线程 obj = t(target=Communication, args=(conn,)) obj.start() # 启动线程 if __name__ == '__main__': pool = mythread.MyThread(3) #主线程干Server的工作 Server('127.0.0.1',9001)
# -*- coding: utf-8 -*- # -*- Author: WangHW -*- import socket whw_client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) whw_client.connect(('127.0.0.1',9001)) while 1: msg = input('>>>:').strip() if not msg: continue whw_client.send(msg.encode('utf-8')) data = whw_client.recv(1024) print('Server Data:',data.decode('utf-8'))
新建一个mythread.py文件,专门进行队列的操作:
# -*- coding: utf-8 -*- # -*- Author: WangHW -*- from threading import Thread from queue import Queue class MyThread: def __init__(self,maxthread): self.maxthread = maxthread #初始化一个Queue对象 self.q = self.queue =Queue(maxthread) #在队列中存放maxthread个对象,起到线程池的作用 for i in range(maxthread): self.q.put(Thread) def put_thread(self): '''put''' self.q.put(Thread) def get_thread(self): '''get''' return self.q.get()
如果设置最大的并发数为3,所以只能同时有3个客户端与服务器端通信: