网络编程之FTP服务端与客户端
#ftp_server import socket import struct import json import os import hashlib server=socket.socket() server.bind(('192.168.15.50',8000)) server.listen(5) while 1: print('sever is working.......') conn,addr=server.accept() while 1: file_info_length_pack=conn.recv(4) file_info_length=struct.unpack('i',file_info_length_pack)[0] file_info_json=conn.recv(file_info_length).decode('utf-8') file_info=json.loads(file_info_json) action=file_info.get('action') file_name=file_info.get('file_name') file_size=file_info.get('file_size') md5=hashlib.md5() with open('put/'+file_name,mode='wb')as f: recv_data_length=0 while recv_data_length <file_size:#file_size是文件总字节长度,recv_data_length是字节长度 data=conn.recv(1024) recv_data_length+=len(data) f.write(data) md5.update(data) print('文件总长度大小为:%s,已经接受了%s'%(file_size,recv_data_length)) else: print('文件上传成功') conn.send('OK'.encode('utf-8')) recv_md5=conn.recv(1024).decode('utf-8') if recv_md5==md5.hexdigest(): print('经对比文件传输无误,OK') conn.send('OK'.encode('utf-8')) break
#ftp_client import socket import struct import os import json import hashlib client=socket.socket() client.connect(('192.168.15.50',8000)) while 1: cmd=input("请输入命令").strip() action,file_name=cmd.split(' ') file_size=os.path.getsize(file_name) file_info={ 'action':action, 'file_name':file_name, 'file_size':file_size } file_info_json=json.dumps(file_info).encode('utf-8') ret=struct.pack('i',len(file_info_json)) client.send(ret) client.send(file_info_json) md5=hashlib.md5() with open(file_name,mode='rb')as f: for line in f: client.send(line) md5.update(line) response1=client.recv(1024).decode('utf-8') if response1=='OK': print('上传完成') client.send(md5.hexdigest().encode('utf-8')) response2=client.recv(1024).decode('utf-8') if response2=='OK': print('经对比文件传输无误') break else: print('传输过程中,文件改变,请重新传输') client.close()