import socket,os,json,struct SHARE_DIR=r'D:\python13期\网络编程\文件处理\SHARE' class FtpServer: def __init__(self,host,port): self.host=host self.port=port self.server=socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.server.bind((self.host,self.port)) self.server.listen(5) def serve_forever(self): print('server starting...') while True: self.conn,self.client_addr=self.server.accept() print(self.client_addr) while True: try: data=self.conn.recv(1024) if not data:break params=json.loads(data.decode('utf-8')) cmd=params[0] if hasattr(self,cmd): func=getattr(self,cmd) func(params) else: print('\033[45mcmd not exists\033[0m') except ConnectionResetError:break self.conn.close() self.server.close() def get(self,params): filename=params[1] filepath=os.path.join(SHARE_DIR,filename) if os.path.exists(filepath): headers = {'filename': filename, 'md5': '123fvs54', 'file_size': os.path.getsize(filepath)} headers_json = json.dumps(headers) headers_bytes = headers_json.encode('utf-8') self.conn.send(struct.pack('i', len(headers_bytes))) self.conn.send(headers_bytes) with open(filepath,'rb')as f: for line in f: self.conn.send(line) def put(self): pass if __name__ == '__main__': server=FtpServer('127.1.2.3',8999) server.serve_forever()