- socket建立网络连接,注意文件分割后,传输完成的检测
- pickle 封装文件信息:文件名、文件大小、md5码
- os 文件路径、文件名、文件大小
- hashlib md5码生成
server端
# Author:Winter Liu is coming! import socket import pickle import hashlib server = socket.socket() server.bind(("127.0.0.1", 10002)) server.listen() conn, addr = server.accept() msg = conn.recv(1024) msg = pickle.loads(msg) filesize = msg["filesize"] m = hashlib.md5() with open(msg["filename"], "wb") as f: while filesize: data = conn.recv(4096) m.update(data) f.write(data) filesize -= len(data) if m.hexdigest() == msg["md5"]: print("translation complete!",m.hexdigest()) else: print("transfer error!") server.close()
client端
# Author:Winter Liu is coming! import socket import pickle import os import hashlib client = socket.socket() server = ("127.0.0.1", 10002) client.connect(server) abs_path = r"C:\PycharmProjects\python level up\Socket网络编程\test.txt" filename = os.path.basename(abs_path) filesize = os.path.getsize(abs_path) m = hashlib.md5() with open(abs_path, "rb") as f: for line in f: m.update(line) dic = {"filename": filename, "filesize": filesize,"md5":m.hexdigest()} print(dic) msg = pickle.dumps(dic) client.send(msg) with open(abs_path, "rb") as f: while filesize: data = f.read(4096) client.send(data) filesize -= len(data) client.close()