python如何解決MD5對文件加密出現粘包的狀況

import socket import os import hashlib server=socket.socket() server.bind(('127.0.0.1',6969)) server.listen() while True: # 保證能與多個通話 conn,addr = server.accept() print('與',addr,'通話') while True: # 保證與某一個一直通話 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 print(file_size) conn.send(str(file_size).encode()) # send the file size conn.recv(1024) # wait the ack from client for line in f: # read the file m.update(line) # apply md5 arithmetic conn.send(line) # don't need to encode because fetch is rb print('md5', m.hexdigest()) # print the finally md5 f.close() conn.send(m.hexdigest().encode()) # send md5 to clientapp

print('send done')

server.close()socket

import socket import hashlib client = socket.socket() client.connect(('127.0.0.1', 6969)) while True: cmd = input('>>:').strip() if len(cmd) == 0: continue if cmd.startswith('get'): client.send(cmd.encode('utf-8')) server_response = client.recv(1024) print('server_response:', server_response) client.send(b'is ready to receive file') file_total_size = int(server_response.decode()) print('file_total_size',file_total_size) 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: # solve the problem can't not receive md5 from server size = 1024 else: size = file_total_size - received_size # received data total=server send the data,except md5 data = client.recv(size) received_size += len(data) f.write(data) m.update(data) else: new_file_md5 = m.hexdigest() print('received has done', received_size, file_total_size) f.close() server_md5 = client.recv(1024) print('server md5 is:', server_md5) print('client md5 is:', new_file_md5) client.close()fetch

相關文章
相關標籤/搜索