Python socket文件传送md5校验

时间:2022-05-13 09:30:58
  • soket_server
import socket,os,hashlib
server = socket.socket()
server.bind(('0.0.0.0',9999))
server.listen()
while True:
conn,addr = server.accept()
print("new conn:",addr)
while True:
print("server on....")
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() #创建md5校验
file_size = os.stat(filename).st_size #获取文件大小
conn.send(str(file_size).encode()) #发送文件大小
conn.recv(1024) #等待ACK交互防止粘包
for line in f:
m.update(line) #递增加密文件
conn.send(line)
print("file md5",m.hexdigest()) #打印16进制md5
f.close()
conn.send(m.hexdigest().encode())
print("send done")
server.close()

  

  • soket_client
import socket
import hashlib
client = socket.socket()
client.connect(('localhost',9999))
while True:
cmd = input(">>:").strip()
if len(cmd) == 0:continue
if cmd.startswith("get"): #是否以get开头
client.send(cmd.encode())
server_response = client.recv(1024)
print("server respoense:",server_response)
client.send(b"ready to recv file")  #发送ACK确认,交互防止send粘包
file_total_size = int(server_response.decode())
received_size = 0
filename = cmd.split()[1]
f = open(filename + ".new","wb")
m = hashlib.md5() #使用md5加密
while received_size < file_total_size:  #判断总数据比递增接收数据大就成立
if file_total_size - received_size > 1024: #数据比recv大就成立
size = 1024
else: #最后一次,还剩多少
size = file_total_size - received_size  #求出剩余recv数值
print("last receive:",size) #最后一次收了多少
data = client.recv(size)
received_size += len(data)  #递增接收数据
m.update(data) #递增接收数据并加密md5
f.write(data)
#print(file_total_size,received_size) #每次发送大小
else:
new_file_md5 = m.hexdigest()
print("file recv done",received_size,file_total_size)
f.close()
server_file_md5 = client.recv(1024)
print("server file md5:",server_file_md5)
print("client file md5:",new_file_md5)
client.close()