import socket,struct,json,os DOWNLOAD_DIR=r'D:\python13期\网络编程\文件处理\DOWNLOAD' class FtpClient: def __init__(self,host,port): self.host=host self.port=port self.client=socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.client.connect((self.host,self.port)) def interactive(self): while True: data=input('>>:').strip() if not data:continue params=data.split() cmd=params[0] if hasattr(self,cmd): func=getattr(self,cmd) func(params) def get(self,params): params_json=json.dumps(params) self.client.send(params_json.encode('utf-8')) headers_size = struct.unpack('i', self.client.recv(4))[0] headers_bytes = self.client.recv(headers_size) headers_json = headers_bytes.decode('utf-8') headers_dic = json.loads(headers_json) print('>>:', headers_dic) filename=headers_dic['filename'] filesize=headers_dic['file_size'] filepath=os.path.join(DOWNLOAD_DIR,filename) with open(filepath,'wb')as f: recv_size = 0 while recv_size < filesize: line=self.client.recv(1024) recv_size += len(line) f.write(line) print('>>:下载成功') if __name__ == '__main__': client=FtpClient('127.1.2.3',8999) client.interactive()