进程池|线程池(同步,异步 阻塞,非阻塞) 多线程:IO密集型 多进程:计算密集型 线程是cpu运行单位,进程是资源单位
from socket import *from threading import Threaddef comunicat(conn): while True: # 通信循环 try: data = conn.recv(1024) if len(data) == 0: break conn.send(data.upper()) except ConnectionResetError: break conn.close()def server(ip, port, backlog=5): server = socket(AF_INET, SOCK_STREAM) server.bind((ip,port)) server.listen(backlog) while True: # 链接循环 conn, client_addr = server.accept() print(client_addr) #通信 t=Thread(target=comunicat,args=(conn,)) t.start()if __name__ == '__main__': s=Thread(target=server,args=('127.0.0.1',8081)) s.start()
from socket import *client=socket(AF_INET,SOCK_STREAM)client.connect(('127.0.0.1',8081))while True: msg=input(">>:").strip() if len(msg) == 0: continue client.send(msg.encode('utf-8')) data=client.recv(1024) print(data.decode('utf-8'))
实现在服务端开启时,可以运行多个客户端,但是有一万个客户端时,服务端会开多个线程来运行,这样就会很耗资源