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

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

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

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

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

客戶(hù)端發(fā)起發(fā)送文件或接收文件的請(qǐng)求,服務(wù)端收到請(qǐng)求后接收或發(fā)送文件,最后進(jìn)行MD5值的校驗(yàn)

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

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

需要從服務(wù)器下載文件時(shí),調(diào)用recvFile函數(shù),收到文件后進(jìn)行MD5校驗(yàn)

client類(lèi)代碼如下

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等待校驗(yàn)...')
    (status, output) = subprocess.getstatusoutput("md5sum " + clientfile + " | awk '{printf $1}'")
    if output == self.md5sum:
     print("文件傳輸成功")
    else:
     print("文件校驗(yàn)不通過(guò)")
     (status, output) = subprocess.getstatusoutput("rm " + clientfile)
   elif self.action.startswith("nofile"):
    print('遠(yuǎn)程源文件/文件夾不存在')
    return "No such file or directory"
  except Exception as e:
   print(e)
   return "error:"+str(e)

server類(lèi)代碼如下

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,并開(kāi)啟服務(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')

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

相關(guān)文章

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

最新評(píng)論

体育| 措勤县| 嫩江县| 九龙城区| 舒兰市| 内乡县| 海伦市| 万荣县| 宜兰县| 突泉县| 桓仁| 腾冲县| 遂平县| 呼和浩特市| 商水县| 大余县| 罗城| 长顺县| 临安市| 四子王旗| 皮山县| 云南省| 柞水县| 崇仁县| 安多县| 扶余县| 藁城市| 綦江县| 宁海县| 兴文县| 顺义区| 长岛县| 江北区| 蓬莱市| 眉山市| 望都县| 建瓯市| 泸溪县| 辽中县| 将乐县| 禹州市|