多线程实现并发:
from socket import * from threading import Thread def talk(conn): while True: try: data = conn.recv(1024) if not data: break conn.send(data.upper()) except ConnectionResetError: break conn.close() def server(ip,port): # 来一个客户端,起一个conn server = socket(AF_INET, SOCK_STREAM) server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) server.bind((ip, port)) server.listen(5) while True: conn,addr = server.accept() t = Thread(target=talk,args=(conn,)) # 子线程响应每个conn t.start() server.close() if __name__ == '__main__': server('127.0.0.1',8087) # 主线程干起server的活
多进程实现并发:
from socket import * from multiprocessing import Process def talk(conn): while True: try: data = conn.recv(1024) if not data: break conn.send(data.upper()) except ConnectionResetError: break conn.close() def server(ip,port): # 来一个客户端,起一个conn server = socket(AF_INET,SOCK_STREAM) server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) server.bind((ip, port)) server.listen(5) while True: conn,addr = server.accept() p = Process(target=talk,args=(conn,)) # 响应每个conn p.start() server.close() if __name__ == '__main__': server('127.0.0.1',8080)
缺点:无限的开进程线程,会导致服务端崩溃。
可用进程池线程池替代。
def server(ip,port): # 来一个客户端,起一个conn server = socket(AF_INET, SOCK_STREAM) server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) server.bind((ip, port)) server.listen(5) while True: conn,addr = server.accept() pool.submit(talk,conn) # 每来一个conn,提交到线程池 server.close() if __name__ == '__main__': pool = ThreadPoolExecutor(2) server('127.0.0.1',8087) # 主线程干起server的活