Server:
import socket,os,hashlib server=socket.socket() server.bind(("localhost",9999))#绑定要监听的端口 server.listen()#开始监听 while True: conn,addr=server.accept()#等待用户输入命令 print("newconn",addr) while True: print("等待新指令") data=conn.recv(1024) if not data: print("客户端断开") break cmd,filename=data.decode().split() print(filename) if os.path.isfile(filename): f = open(filename,"rb") m = hashlib.md5() file_size=os.stat(filename).st_size conn.send(str(file_size).encode())#send file size conn.recv(1024)#wait for ack for line in f: m.update(line) conn.send(line) print("file md5",m.hexdigest()) f.close() conn.send(m.hexdigest().encode())#send md5 print("send done") server.close()
client:
import socket,os,hashlib client=socket.socket() client.connect(("localhost",9999)) while True: cmd = input(">>:".strip()) if len(cmd) ==0:continue if cmd.startswith("get"): client.send(cmd.encode()) server_respose=client.recv(1024)#文件大小 print("server respose",server_respose) client.send(b"ready to recv file") file_total_size = int(server_respose.decode()) received_size=0 filename=cmd.split()[1] f = open(filename+".new","wb")#复制新文件 m = hashlib.md5() while received_size<file_total_size: if file_total_size - received_size > 1024:#接收不止一次 size=1024 else:#最后一次接收 size=file_total_size-received_size print("last receive",size) data=client.recv(size) received_size+=len(data) m.update(data) f.write(data) else: new_file_md5=m.hexdigest() print("file recv done",received_size,file_total_size) f.close() server_file_md5=client.recv(1024)#最后接收服务器返回的md5 print("server file md5",server_file_md5) print("client file md5",new_file_md5) client.close
时间: 2024-10-09 01:17:08