socket+threading自定义线程池实现并发
"""
user-defined threading-pool Concurrency-server.
不保存cnn, 扔进去,读取执行,结束.
总结:
线程结束了就结束了. 所以如何实现线程不结束得去处理任务才是问题.
流程如下.
创建queue来put socket任务和get socket任务,
创建threading-pool让其中线程能循环get socket任务.
so 循环 apply_async不停put socket任务就完了.
如果主进程末尾加上join则会等待每个传入的socket任务处理结束, 使得不能实现多client访问, 所以不使用join来等待任务结束.
大概是这样.
"""
import threading
import queue
import socket
class DeThread:
def __init__(self, server_queue, server_number):
self.queue = server_queue
for i in range(1, server_number + 1):
de_thread = threading.Thread(target=self.work, name="{}".format(i), daemon=True)
de_thread.start()
def work(self):
print("[+] Customer service {} online.".format(threading.current_thread().name))
while True:
try:
client_mission, client_address = self.queue.get()
client_mission.send(b"welcome to server.")
print("[+] {} is connected.".format(client_address))
while True:
client_data = client_mission.recv(1024)
if not client_data == b"quit":
print("[+] {} talk: {}".format(client_address, client_data))
client_mission.send(b"Received of information.")
else:
client_mission.send(b"Goodbye.")
print("[+] {} is close".format(client_address))
client_mission.close()
break
except Exception as error_work:
print("[-] Error Work: {}".format(error_work))
finally:
self.queue.task_done()
def apply_async(self, client_connect):
self.queue.put(client_connect)
def join(self):
self.queue.join()
def func(server):
connect, address = server.accept()
connects = (connect, address)
return connects
if __name__ == '__main__':
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((socket.gethostbyname(socket.gethostname()), 4444))
server.listen(5)
serverQueue = queue.Queue()
sPool = DeThread(serverQueue, 2)
print("[+] Start listen......")
while True:
try:
sPool.apply_async(func(server))
except Exception as error_pool:
print("[-] Error Pool:{}".format(error_pool))