解决粘包情况
客户端
import socket,struct,sys,json # 系统平台 def check_platfrom(): if sys.platform == "win32": return "gbk" elif sys.platform == "linux2": return "utf-8" code = check_platfrom() phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ip_addr = ("127.0.0.1", 8000) phone.connect(ip_addr) while True: inp = input(">>>: ").strip() if not inp:continue phone.send(inp.encode(code)) # 1 收报头的长度 head_data = phone.recv(4) header_size = struct.unpack("i",head_data)[0] # 2 再收报头 header_json = phone.recv(header_size) # 3 从json文件解析文件 header_file = json.loads(header_json) data_size = header_file["total_size"] print(header_file) recv_size = 0 recv_data =b'' # 4 接收真实的数据 while recv_size < data_size: data = phone.recv(1024) # 每次接收的数据 recv_data +=data recv_size += len(data) print(recv_data.decode(code)) phone.close()
服务端
import socket, struct,subprocess,sys,json # 系统平台 def check_platfrom(): if sys.platform == "win32": return "gbk" elif sys.platform == "linux2": return "utf-8" code = check_platfrom() phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ip_addr = ("127.0.0.1", 8000) phone.bind(ip_addr) phone.listen(5) while True: conn, client_addr = phone.accept() print(client_addr) while True: try: command = conn.recv(1024) if not command:break #适用于linux操作系统 obj = subprocess.Popen(command.decode(code), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = obj.stdout.read() stderr = obj.stderr.read() total_size = len(stdout) + len(stderr) # 1制作报头 head_dic = {"filename":"a.txt", "md5":22222, "total_size":total_size} header_json = json.dumps(head_dic) header_size = len(header_json) # 2发送 head_data conn.send(struct.pack('i',header_size)) # 3发送 json_file conn.send(header_json.encode(code)) # 4发送 命令的结果 conn.send(stdout) conn.send(stderr) print(total_size) except ConnectionResetError: break conn.close() phone.close()