最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于python3實現(xiàn)socket文件傳輸和校驗

 更新時間:2018年07月28日 11:38:40   作者:m4_Sean  
這篇文章主要為大家詳細介紹了基于python3實現(xiàn)socket文件傳輸和校驗,具有一定的參考價值,感興趣的小伙伴們可以參考一下

基于socket的文件傳輸并進行MD5值校驗,供大家參考,具體內(nèi)容如下

文件傳輸分為兩個類,一個是服務(wù)端,一個是客戶端。

客戶端發(fā)起發(fā)送文件或接收文件的請求,服務(wù)端收到請求后接收或發(fā)送文件,最后進行MD5值的校驗

socket數(shù)據(jù)通過struct模塊打包

需要發(fā)送文件到服務(wù)端時,調(diào)用sendFile函數(shù),struct包內(nèi)包含文件信息、文件大小、文件MD5等信息,服務(wù)端接收到文件后進行MD5值校驗,校驗成功后則返回成功

需要從服務(wù)器下載文件時,調(diào)用recvFile函數(shù),收到文件后進行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("目標(biāo)文件/文件夾不存在")
    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('本地目標(biāo)文件/文件夾不存在')
   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()

調(diào)用server,并開啟服務(wù)

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()

調(diào)用client,發(fā)送/接受文件

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')

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python創(chuàng)建文件夾與文件的快捷方法

    Python創(chuàng)建文件夾與文件的快捷方法

    這篇文章主要給大家介紹了關(guān)于Python創(chuàng)建文件夾與文件的快捷方法以及批量創(chuàng)建文件夾的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-12-12
  • Python入門教程(三十九)Python的NumPy安裝與入門

    Python入門教程(三十九)Python的NumPy安裝與入門

    這篇文章主要介紹了Python入門教程(三十九)Python的NumPy安裝與入門,NumPy 是一個Python包,它是一個由多維數(shù)組對象和用于處理數(shù)組的例程集合組成的庫,,需要的朋友可以參考下
    2023-05-05
  • Python實現(xiàn)通過解析域名獲取ip地址的方法分析

    Python實現(xiàn)通過解析域名獲取ip地址的方法分析

    這篇文章主要介紹了Python實現(xiàn)通過解析域名獲取ip地址的方法,結(jié)合實例形式總結(jié)分析了兩種比較常見的解析域名對應(yīng)IP地址相關(guān)操作技巧,需要的朋友可以參考下
    2019-05-05
  • Python使用shutil模塊實現(xiàn)文件拷貝

    Python使用shutil模塊實現(xiàn)文件拷貝

    這篇文章主要介紹了Python使用shutil模塊實現(xiàn)文件拷貝,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-07-07
  • python使用Matplotlib改變坐標(biāo)軸的默認位置

    python使用Matplotlib改變坐標(biāo)軸的默認位置

    這篇文章主要為大家詳細介紹了python使用Matplotlib改變坐標(biāo)軸的默認位置,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-10-10
  • 對sklearn的使用之?dāng)?shù)據(jù)集的拆分與訓(xùn)練詳解(python3.6)

    對sklearn的使用之?dāng)?shù)據(jù)集的拆分與訓(xùn)練詳解(python3.6)

    今天小編就為大家分享一篇對sklearn的使用之?dāng)?shù)據(jù)集的拆分與訓(xùn)練詳解(python3.6),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • python中單下劃線_的常見用法總結(jié)

    python中單下劃線_的常見用法總結(jié)

    這篇文章主要介紹了python中單下劃線_的常見用法總結(jié),其實很多(不是所有)關(guān)于下劃線的使用都是一些約定俗成的慣例,而不是真正對python解釋器有影響,感興趣的朋友跟隨腳本之家小編一起看看吧
    2018-07-07
  • 2021年的Python 時間軸和即將推出的功能詳解

    2021年的Python 時間軸和即將推出的功能詳解

    這篇文章主要介紹了2021年的Python 時間軸和即將推出的功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-07-07
  • Python操作MongoDB數(shù)據(jù)庫PyMongo庫使用方法

    Python操作MongoDB數(shù)據(jù)庫PyMongo庫使用方法

    這篇文章主要介紹了Python操作MongoDB數(shù)據(jù)庫PyMongo庫使用方法,本文講解了創(chuàng)建連接、連接數(shù)據(jù)庫、連接聚集、查看全部聚集名稱、查看聚集的一條記錄等操作方法,需要的朋友可以參考下
    2015-04-04
  • python 消費 kafka 數(shù)據(jù)教程

    python 消費 kafka 數(shù)據(jù)教程

    今天小編就為大家分享一篇python 消費 kafka 數(shù)據(jù)教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12

最新評論

宁河县| 西盟| 屏山县| 黑山县| 扬中市| 成武县| 南阳市| 扶沟县| 长宁县| 尤溪县| 柳河县| 土默特右旗| 大埔县| 东乌珠穆沁旗| 井冈山市| 孙吴县| 九龙城区| 孝昌县| 延川县| 玉龙| 宁阳县| 岐山县| 河津市| 友谊县| 西平县| 呼玛县| 安岳县| 大埔区| 涟源市| 元谋县| 塔城市| 峨眉山市| 龙游县| 莱阳市| 威海市| 邯郸县| 芜湖县| 扬州市| 衡山县| 黑龙江省| 东台市|