功能描述:实现简单的文件上传和下载功能
程序分三部分:
① ftp_opr.py 上传下载功能,需与其他程序在一起
② ftp_server.py 服务端程序
③ ftp_client.py 客户端程序
#!/usr/bin/env python # -*- coding:utf-8 -*- #filename:ftp_opr.py import socket,os,json def send_file(socket_object,filename): ####传入套接字对象和文件名,下同 fk = open(filename, ‘rb‘) file_size = os.path.getsize(filename) dict = {‘filename‘:filename,‘file_size‘:file_size} socket_object.send(json.dumps(dict).encode(‘utf-8‘)) print(‘准备发送的文件名:‘,dict[‘filename‘],‘文件大小:‘,dict[‘file_size‘]) socket_object.recv(1024) ####等待一个save_file发过来的无用信号,用于防止粘包 socket_object.send(fk.read()) fk.close() def save_file(socket_object,filename): name_size_dict = json.loads(socket_object.recv(1024).decode(‘utf-8‘)) print(‘准备接收的文件名:‘,name_size_dict[‘filename‘],‘文件大小:‘, name_size_dict[‘file_size‘]) socket_object.send(b‘ready‘) ####发送一个无用的信号,用于防止粘包 #filename = name_size_dict[‘filename‘] ####调用该方法需要输入filename参数,同时传过来的dict中已经包含filename,所以忽略其一 file_size = name_size_dict[‘file_size‘] fk = open(filename+‘.new‘, ‘wb‘) receive_size = 0 while file_size > receive_size: data = socket_object.recv(1024) fk.write(data) receive_size += len(data) print(len(data), receive_size, file_size) print(‘文件接收完毕!‘) fk.close()
#!/usr/bin/env python # -*- coding:utf-8 -*- #filename:ftp_server.py from ftp_opr import send_file,save_file def ftp_server(): sk = socket.socket() sk.bind((‘0.0.0.0‘,9999)) ####绑定本机网卡地址和端口 sk.listen() while True: conn,addr = sk.accept() print(‘新的连接:‘,addr) while True: cmd = conn.recv(1024).decode(‘utf-8‘) if len(cmd) == 0: print(‘客户端断开了‘) break elif cmd.split()[0] == ‘get‘: ####对应客户端下载功能 filename= cmd.split()[1] print(cmd) send_file(conn, filename) elif cmd.split()[0] == ‘put‘: ####对应客户端上传功能 filename= cmd.split()[1] print(cmd) save_file(conn, filename) else: ‘‘‘保留功能部分‘‘‘ pass sk.close() if __name__ == ‘__main__‘: ftp_server()
#!/usr/bin/env python # -*- coding:utf-8 -*- #filename:ftp_client.py import socket,os,json from ftp_opr import send_file,save_file def ftp_client(): sk = socket.socket() sk.connect((‘127.0.0.1‘,9999)) ####连接服务器地址和端口 while True: cmd = input(‘>>>:‘) if len(cmd) == 0:continue elif cmd == ‘q‘: exit() elif len(cmd.split()) > 2: print(‘输入参数过多,请使用 put/get + 1个文件名‘) elif cmd.split()[0] == ‘get‘: ####下载功能 filename= cmd.split()[1] sk.send(bytes(cmd.encode(‘utf-8‘))) save_file(sk, filename) elif cmd.split()[0] == ‘put‘: ####下载功能 filename= cmd.split()[1] sk.send(bytes(cmd.encode(‘utf-8‘))) send_file(sk, filename) else: print(‘输入错误,请输入 put/get + 文件名‘) pass sk.close() if __name__ == ‘__main__‘: ftp_client()
时间: 2024-10-13 01:14:56