利用隊列Queue實現一個多併發「線程池」效果的Socket程序

  本例經過利用類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)
Server
# -*- 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'))
Client

  新建一個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()
mythread

  若是設置最大的併發數爲3,因此只能同時有3個客戶端與服務器端通訊:socket

相關文章
相關標籤/搜索