并发编程-基于多进程实现并发套接字通信
服务端:
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 ConnectionRefusedError: break conn.close() def server(ip,port): server=socket(AF_INET,SOCK_STREAM) server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) server.bind((ip,port)) server.listen(5) while True: conn, client_addr = server.accept() p = Process(target=talk,args=(conn,)) p.start() server.close() if __name__ == '__main__': server('127.0.0.1',8080)
客户端:
from socket import * client=socket(AF_INET,SOCK_STREAM) client.connect(('127.0.0.1',8080)) while True: msg = input('>>:').strip() if not msg : continue client.send(msg.encode('utf-8')) data=client.recv(1024) print(data.decode('utf-8'))