思路:
读取文件名
检测文件是否存在
打开文件
检测文件大小
发送文件大小和MD5值给客户端
等客户端确认
开始边读边发数据
MD5验证
# 服务器端 import socket import os import hashlib server = socket.socket() server.bind(("localhost", 6969)) # 绑定监听端口 server.listen(5) # 监听 print("监听开始..") while True: conn, addr = server.accept() # 等待连接 print("conn:", conn, "\naddr:", addr) # conn连接实例 while True: data = conn.recv(1024) # 接收 if not data: # 客户端已断开 print("客户端断开连接") break print("收到的命令:", data.decode("utf-8")) cmd, filename = data.decode("utf-8").split(" ") if cmd =="get": if os.path.isfile(filename): # 判断文件存在 # 1.先发送文件大小,让客户端准备接收 size = os.stat(filename).st_size #获取文件大小 conn.send(str(size).encode("utf-8")) # 发送数据长度 print("发送的大小:", size) # 2.发送文件内容 conn.recv(1024) # 接收确认 m = hashlib.md5() f = open(filename, "rb") for line in f: conn.send(line) # 发送数据 m.update(line) f.close() # 3.发送md5值进行校验 md5 = m.hexdigest() conn.send(md5.encode("utf-8")) # 发送md5值 print("md5:", md5) server.close()
# 客户端 import socket import os import hashlib client = socket.socket() # 生成socket连接对象 ip_port =("localhost", 6969) # 地址和端口号 client.connect(ip_port) # 连接 print("服务器已连接") while True: content = input(">>") if len(content)==0: continue # 如果传入空字符会阻塞 if content.startswith("get"): client.send(content.encode("utf-8")) # 传送和接收都是bytes类型 # 1.先接收长度,建议8192 server_response = client.recv(1024) file_size = int(server_response.decode("utf-8")) print("接收到的大小:", file_size) # 2.接收文件内容 client.send("准备好接收".encode("utf-8")) # 接收确认 filename = "new" + content.split(" ")[1] f = open(filename, "wb") received_size = 0 m = hashlib.md5() while received_size < file_size: size = 0 # 准确接收数据大小,解决粘包 if file_size - received_size > 1024: # 多次接收 size = 1024 else: # 最后一次接收完毕 size = file_size - received_size data = client.recv(size) # 多次接收内容,接收大数据 data_len = len(data) received_size += data_len print("已接收:", int(received_size/file_size*100), "%") m.update(data) f.write(data) f.close() print("实际接收的大小:", received_size) # 解码 # 3.md5值校验 md5_sever = client.recv(1024).decode("utf-8") md5_client = m.hexdigest() print("服务器发来的md5:", md5_sever) print("接收文件的md5:", md5_client) if md5_sever == md5_client: print("MD5值校验成功") else: print("MD5值校验失败") client.close()
提示:客户端输入格式为:
get filename