您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關基于python3實現socket文件傳輸和校驗的案例的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
1、云計算,典型應用OpenStack。2、WEB前端開發,眾多大型網站均為Python開發。3.人工智能應用,基于大數據分析和深度學習而發展出來的人工智能本質上已經無法離開python。4、系統運維工程項目,自動化運維的標配就是python+Django/flask。5、金融理財分析,量化交易,金融分析。6、大數據分析。
基于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')
感謝各位的閱讀!關于“基于python3實現socket文件傳輸和校驗的案例”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。