1.基于线程池实现并发套接字通讯:因为套接字涉及地是I/O密集模型,因此使用多线程会有高效率
'''
服务器
'''#基于线程池完成并发的套接字通讯
from socket import *
from threading import Thread
from concurrent.futures import ThreadPoolExecutordef communicate(conn):while True:try:data = conn.recv(1024)#1024表示接收的字节最大量是1024bytesprint('这是客户端的请求数据',data)conn.send(data.upper())except ConnectionResetError:breakdef connect(ip,port):phone = socket(AF_INET,SOCK_STREAM)phone.bind((ip,port))phone.listen(5)while True:res = phone.accept()conn,client_addr = rest = Thread(target=communicate,args=(conn,))t.start()phone.close()if __name__ == '__main__':pool = ThreadPoolExecutor(5)pool.submit(connect,'127.0.0.1',8081)'''
客户端
'''import socketdef client(ip,port):phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)phone.connect((ip,port))while True:cmd = input("请输入命名:")if not cmd:continuephone.send(cmd.encode('utf-8'))res = phone.recv(1024)#接收小于1024bytes的数据print('服务器返回来的数据:',res.decode('gbk'))print('*'*50)#5、关闭套接字phonephone.close()if __name__ == '__main__':client('127.0.0.1',8081)
2.基于gevent协程实现并发套接字通讯
'''
服务器
'''#基于gevent完成并发的套接字通讯
from socket import *
from threading import Thread
from gevent import spawn,monkeymonkey.patch_all()
def communicate(conn):while True:try:data = conn.recv(1024)#1024表示接收的字节最大量是1024bytesprint('这是客户端的请求数据',data)conn.send(data.upper())except ConnectionResetError:breakdef connect(ip,port):phone = socket(AF_INET,SOCK_STREAM)phone.bind((ip,port))phone.listen(5)while True:res = phone.accept()conn,client_addr = resspawn(communicate,conn).join()if __name__ == '__main__':g = spawn(connect,'127.0.0.1',8090)g.join()'''
客户端
'''
import socket
from threading import currentThread,Threaddef client():phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)phone.connect(('127.0.0.1',8090))while True:# cmd = input("请输入命名:")# cmd =# if not cmd:continuephone.send(('%s hello'%currentThread().getName()).encode('utf-8'))res = phone.recv(1024)#接收小于1024bytes的数据print('服务器返回来的数据:',res.decode('gbk'))print('*'*50)#5、关闭套接字phonephone.close()if __name__ == '__main__':for i in range(500):t = Thread(target=client)t.start()