服务器端要先根据客户端要下载的文件进行判断是否存在,还要根据文件大小来进行传送,最后还要比对文件的md5值来判断传送的文件是否正确,通过判断剩余字节来解决粘包问题
服务器端
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import socket import os import hashlib server = socket.socket() server.bind(('127.0.0.1',8080)) server.listen() print('等待客户端连接') while True: conn,addr = server.accept() print('当前连接客户端:',addr) while True: print('等待客户端下载指令') data = conn.recv(1024) if not data: print('客户端已断开连接') break filename = data.decode() 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()) #发送文件大小 conn.recv(1024) #等待确认 for line in f: conn.send(line) #发送文件 m.update(line) print("文件md5值:", m.hexdigest()) conn.send(m.hexdigest().encode()) #发送md5值 f.close() print('发送完成') server.close()
客户端
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import socket import hashlib client = socket.socket() client.connect(('127.0.0.1',8080)) while True: cmd = input('请输入需要下载的文件:').strip() client.send(cmd.encode()) if len(cmd) == 0:continue server_file_size = client.recv(1024) client.send('准备好接收文件了'.encode()) server_file_size = int(server_file_size.decode()) #要接收的文件大小 received_size = 0 filename = cmd f = open(filename+'_new','wb') m = hashlib.md5() while received_size < server_file_size: if server_file_size - received_size >1024: #判断要接收的次数是否大于一次 left_size = 1024 else: left_size = server_file_size - received_size data = client.recv(left_size) received_size += len(data) m.update(data) f.write(data) else: new_file_md5 = m.hexdigest() print('下载完成',received_size,server_file_size) f.close() server_file_md5 = client.recv(1024) if new_file_md5.encode() == server_file_md5: print('下载文件正确') else: print('下载了错误文件') client.close()
运行结果
服务器端
文件传输结果