通过socket实现文件发送,并解决粘包问题
一、socket文件发送_server(服务器端)
1 # Author:David Liu 2 # Be Happy! 3 ''' 4 FTP server 5 1.读取文件名 6 2.检测文件是否存在 7 3.打开文件 8 4.检测文件大小 9 5.发送文件大小给客户端 10 6.等待客户端确认 11 7.开始边读边发数据 12 8.发送md5 13 ''' 14 import socket,os,time,hashlib 15 server=socket.socket() 16 server.bind(('localhost',9999)) 17 server.listen() 18 while True: 19 conn,addr=server.accept() 20 print("new conn",addr) 21 while True: 22 print("等待新指令") 23 data=conn.recv(1024) 24 if not data: 25 print("客户端已断开") 26 break 27 28 cmd,filename=data.decode().split() 29 print(filename) 30 if os.path.isfile(filename): 31 f=open(filename,'rb') 32 m=hashlib.md5() 33 file_size=os.stat(filename).st_size 34 conn.send(str(file_size).encode()) 35 conn.recv(1024) 36 for line in f: 37 m.update(line) 38 conn.send(line) 39 print("file md5",m.hexdigest()) 40 conn.send(m.hexdigest().encode()) 41 f.close() 42 43 print("send done") 44 server.close()
二、socket文件发送_client(客户端)
1 # Author:David Liu 2 # Be Happy! 3 4 import socket 5 import hashlib 6 client=socket.socket() 7 8 client.connect(('localhost',9999)) 9 10 while True: 11 cmd=input(">>:").strip() 12 if len(cmd)==0:continue 13 if cmd.startswith("get"): 14 client.send(cmd.encode()) 15 server_response=client.recv(1024) 16 print("文件大小",server_response) 17 client.send(b"ready to recevie") 18 file_total_size=int(server_response.decode()) 19 received_size=0 20 filename=cmd.split()[1] 21 f=open(filename+'.new','wb') 22 23 m=hashlib.md5() 24 25 while received_size<file_total_size: 26 #解决粘包 27 if file_total_size-received_size>1024:#表示要收不止一次 28 size=1024 29 else:#最后一次了,剩多少收多少 30 size=file_total_size-received_size 31 print("last receive:", size) 32 #---^ 33 data=client.recv(size) 34 received_size+=len(data) 35 m.update(data) 36 f.write(data) 37 print(file_total_size,received_size) 38 39 else: 40 new_file_md5=m.hexdigest() 41 print("文件接收完毕!") 42 f.close() 43 server_filr_md5=client.recv(1024) 44 print("server file md5:",server_filr_md5) 45 print("client file md5:",new_file_md5) 46 47 client.close()
功能片段,留存……
感觉越来越难了哈哈哈,挺住!
2019年5月23日