帝王谷资源网 Design By www.wdxyy.com
基于socket的文件传输并进行MD5值校验,供大家参考,具体内容如下
文件传输分为两个类,一个是服务端,一个是客户端。
客户端发起发送文件或接收文件的请求,服务端收到请求后接收或发送文件,最后进行MD5值的校验
socket数据通过struct模块打包
需要发送文件到服务端时,调用sendFile函数,struct包内包含文件信息、文件大小、文件MD5等信息,服务端接收到文件后进行MD5值校验,校验成功后则返回成功
需要从服务器下载文件时,调用recvFile函数,收到文件后进行MD5校验
client类代码如下
import socket import struct,os import subprocess dataFormat='8s32s100s100sl' class fileClient(): def __init__(self,addr): self.addr = addr self.action = '' self.fileName = '' self.md5sum = '' self.clientfilePath = '' self.serverfilePath = '' self.size = 0 def struct_pack(self): ret = struct.pack(dataFormat,self.action.encode(),self.md5sum.encode(),self.clientfilePath.encode(), self.serverfilePath.encode(),self.size) return ret def struct_unpack(self,package): self.action,self.md5sum,self.clientfilePath,self.serverfilePath,self.size = struct.unpack(dataFormat,package) self.action = self.action.decode().strip('\x00') self.md5sum = self.md5sum.decode().strip('\x00') self.clientfilePath = self.clientfilePath.decode().strip('\x00') self.serverfilePath = self.serverfilePath.decode().strip('\x00') def sendFile(self,clientfile,serverfile): if not os.path.exists(clientfile): print('源文件/文件夹不存在') return "No such file or directory" self.action = 'upload' (status, output) = subprocess.getstatusoutput("md5sum " + clientfile + " | awk '{printf $1}'") if status == 0: self.md5sum = output else: return "md5sum error:"+status self.size = os.stat(clientfile).st_size self.serverfilePath = serverfile self.clientfilePath = clientfile ret = self.struct_pack() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect(self.addr) s.send(ret) recv = s.recv(1024) if recv.decode() == 'dirNotExist': print("目标文件/文件夹不存在") return "No such file or directory" elif recv.decode() == 'ok': fo = open(clientfile, 'rb') while True: filedata = fo.read(1024) if not filedata: break s.send(filedata) fo.close() recv = s.recv(1024) if recv.decode() == 'ok': print("文件传输成功") s.close() return 0 else: s.close() return "md5sum error:md5sum is not correct!" except Exception as e: print(e) return "error:"+str(e) def recvFile(self,clientfile,serverfile): if not os.path.isdir(clientfile): filePath,fileName = os.path.split(clientfile) else: filePath = clientfile if not os.path.exists(filePath): print('本地目标文件/文件夹不存在') return "No such file or directory" self.action = 'download' self.clientfilePath = clientfile self.serverfilePath = serverfile s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect(self.addr) ret = self.struct_pack() s.send(ret) recv = s.recv(struct.calcsize(dataFormat)) self.struct_unpack(recv) if self.action.startswith("ok"): if os.path.isdir(clientfile): fileName = (os.path.split(serverfile))[1] clientfile = os.path.join(clientfile, fileName) self.recvd_size = 0 file = open(clientfile, 'wb') while not self.recvd_size == self.size: if self.size - self.recvd_size > 1024: rdata = s.recv(1024) self.recvd_size += len(rdata) else: rdata = s.recv(self.size - self.recvd_size) self.recvd_size = self.size file.write(rdata) file.close() print('\n等待校验...') (status, output) = subprocess.getstatusoutput("md5sum " + clientfile + " | awk '{printf $1}'") if output == self.md5sum: print("文件传输成功") else: print("文件校验不通过") (status, output) = subprocess.getstatusoutput("rm " + clientfile) elif self.action.startswith("nofile"): print('远程源文件/文件夹不存在') return "No such file or directory" except Exception as e: print(e) return "error:"+str(e)
server类代码如下
import socket import struct,os import subprocess import socketserver dataFormat='8s32s100s100sl' class fileServer(socketserver.StreamRequestHandler): def struct_pack(self): ret = struct.pack(dataFormat, self.action.encode(), self.md5sum.encode(), self.clientfilePath.encode(), self.serverfilePath.encode(), self.size) return ret def struct_unpack(self, package): self.action, self.md5sum, self.clientfilePath, self.serverfilePath, self.size = struct.unpack(dataFormat, package) self.action = self.action.decode().strip('\x00') self.md5sum = self.md5sum.decode().strip('\x00') self.clientfilePath = self.clientfilePath.decode().strip('\x00') self.serverfilePath = self.serverfilePath.decode().strip('\x00') def handle(self): print('connected from:', self.client_address) fileinfo_size = struct.calcsize(dataFormat) self.buf = self.request.recv(fileinfo_size) if self.buf: self.struct_unpack(self.buf) print("get action:"+self.action) if self.action.startswith("upload"): try: if os.path.isdir(self.serverfilePath): fileName = (os.path.split(self.clientfilePath))[1] self.serverfilePath = os.path.join(self.serverfilePath, fileName) filePath,fileName = os.path.split(self.serverfilePath) if not os.path.exists(filePath): self.request.send(str.encode('dirNotExist')) else: self.request.send(str.encode('ok')) recvd_size = 0 file = open(self.serverfilePath, 'wb') while not recvd_size == self.size: if self.size - recvd_size > 1024: rdata = self.request.recv(1024) recvd_size += len(rdata) else: rdata = self.request.recv(self.size - recvd_size) recvd_size = self.size file.write(rdata) file.close() (status, output) = subprocess.getstatusoutput("md5sum " + self.serverfilePath + " | awk '{printf $1}'") if output == self.md5sum: self.request.send(str.encode('ok')) else: self.request.send(str.encode('md5sum error')) except Exception as e: print(e) finally: self.request.close() elif self.action.startswith("download"): try: if os.path.exists(self.serverfilePath): (status, output) = subprocess.getstatusoutput("md5sum " + self.serverfilePath + " | awk '{printf $1}'") if status == 0: self.md5sum = output self.action = 'ok' self.size = os.stat(self.serverfilePath).st_size ret = self.struct_pack() self.request.send(ret) fo = open(self.serverfilePath, 'rb') while True: filedata = fo.read(1024) if not filedata: break self.request.send(filedata) fo.close() else: self.action = 'nofile' ret = self.struct_pack() self.request.send(ret) except Exception as e: print(e) finally: self.request.close()
调用server,并开启服务
import fileSocket import threading import socketserver import time serverIp = '127.0.0.1' serverPort = 19821 serverAddr = (serverIp,serverPort) class fileServerth(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.create_time = time.time() self.local = threading.local() def run(self): print("fileServer is running...") fileserver.serve_forever() fileserver = socketserver.ThreadingTCPServer(serverAddr, fileSocket.fileServer) fileserverth = fileServerth() fileserverth.start()
调用client,发送/接受文件
import fileSocket serverIp = '127.0.0.1' serverPort = 19821 serverAddr = (serverIp,serverPort) fileclient = fileSocket.fileClient(serverAddr) fileclient.sendFile('fromClientPath/file','toServerPath/file') fileclient.recvFile('toClientPath/file','fromServerPath/file')
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
帝王谷资源网 Design By www.wdxyy.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
帝王谷资源网 Design By www.wdxyy.com
暂无评论...
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。
更新日志
2024年12月28日
2024年12月28日
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]