功能:使用socket实现文件的收发,客户端发送[get 文件名],在客户端接收服务端的文件,接受后校验MD5值。
client端:
import socket,hashlib client=socket.socket() client.connect((\'localhost\',9999)) while True: msg=input(\'>>>\').strip() if len(msg)==0: continue if msg.startswith(\'get\'): client.send(msg.encode(\'utf-8\')) server_response=client.recv(1024) print(\'file size:\',server_response.decode()) client.send(\'...\'.encode(\'utf-8\')) file_total_size=int(server_response.decode()) recv_size=0 filename=msg.split()[1] f=open(filename+\'_new\',\'wb\') m=hashlib.md5() while recv_size<file_total_size: data=client.recv(1024) recv_size+=len(data) f.write(data) m.update(data) print(\'recv:%d/%d\'%(recv_size,file_total_size)) else: print(\'recv done...\') f.close() new_file_md5=m.hexdigest() client.send(\'recv done\'.encode(\'utf-8\')) server_files_md5=client.recv(1024).decode() print(\'server_files_md5:\',server_files_md5) print(\'new_file_md5:\',new_file_md5) client.close()
server端:
import socket,os,hashlib server=socket.socket() server.bind((\'localhost\',9999)) print(\'waiting...\') server.listen() while True: conn,addr=server.accept() print(\'new conn:\',addr) while True: data=conn.recv(1024).decode() if not data: print(\'客户端断开...\') break print(\'data\',data) cmd,filename=data.split() print(\'cmd:\',cmd) print(\'filename:\',filename) if os.path.isfile(filename): file_size=os.stat(filename).st_size conn.send(str(file_size).encode(\'utf-8\')) conn.recv(1024).decode()#防粘包 f = open(filename,\'rb\') m=hashlib.md5() for line in f: m.update(line) conn.send(line)#按行发送 res_md5=m.hexdigest() print(\'MD5:\',res_md5) f.close() conn.recv(1024).decode()#防粘包 conn.send(res_md5.encode(\'utf-8\'))#发送MD5 print(\'send done\') server.close()
请发表评论