基于python3实现socket文件传输和校验


Posted in Python onJuly 28, 2018

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python列表推导式的使用方法
Nov 21 Python
python通过装饰器检查函数参数数据类型的方法
Mar 13 Python
简介Python设计模式中的代理模式与模板方法模式编程
Feb 02 Python
解读! Python在人工智能中的作用
Nov 14 Python
python射线法判断检测点是否位于区域外接矩形内
Jun 28 Python
新手如何发布Python项目开源包过程详解
Jul 11 Python
Python Django基础二之URL路由系统
Jul 18 Python
Python pandas自定义函数的使用方法示例
Nov 20 Python
在matplotlib中改变figure的布局和大小实例
Apr 23 Python
python多进程使用函数封装实例
May 02 Python
Python读取Excel一列并计算所有对象出现次数的方法
Sep 04 Python
详解selenium + chromedriver 被反爬的解决方法
Oct 28 Python
python多进程实现文件下载传输功能
Jul 28 #Python
python如何生成网页验证码
Jul 28 #Python
python3利用tcp实现文件夹远程传输
Jul 28 #Python
python使用tornado实现简单爬虫
Jul 28 #Python
python编写简易聊天室实现局域网内聊天功能
Jul 28 #Python
对tensorflow 的模型保存和调用实例讲解
Jul 28 #Python
Python Socket编程之多线程聊天室
Jul 28 #Python
You might like
PHP直接修改表内容DataGrid功能实现代码
2015/09/24 PHP
PHP操作MySQL中BLOB字段的方法示例【存储文本与图片】
2017/09/15 PHP
php ajax数据传输和响应方法
2018/08/21 PHP
JQuery 前台切换网站的样式实现
2009/06/22 Javascript
JS在IE和FF下attachEvent,addEventListener学习笔记
2009/11/26 Javascript
IE浏览器不支持getElementsByClassName的解决方法
2014/08/27 Javascript
原生JS实现美图瀑布流布局赏析
2015/09/07 Javascript
jQuery操作Table技巧大汇总
2016/01/23 Javascript
js变量提升深入理解
2016/09/16 Javascript
除Console.log()外更多的Javascript调试命令
2018/01/24 Javascript
JS中判断某个字符串是否包含另一个字符串的五种方法
2018/05/03 Javascript
微信小程序自定义音乐进度条的实例代码
2018/08/28 Javascript
微信小程序--获取用户地理位置名称(无须用户授权)的方法
2019/04/29 Javascript
实例详解vue中的$root和$parent
2019/04/29 Javascript
js实现多图和单图上传显示
2019/12/18 Javascript
JS手写一个自定义Promise操作示例
2020/03/16 Javascript
JavaScript实现手机号码 3-4-4格式并控制新增和删除时光标的位置
2020/06/02 Javascript
JavaScript图片旋转效果实现方法详解
2020/06/28 Javascript
Vue项目中数据的深度监听或对象属性的监听实例
2020/07/17 Javascript
Python translator使用实例
2008/09/06 Python
pandas groupby 分组取每组的前几行记录方法
2018/04/20 Python
Python中修改字符串的四种方法
2018/11/02 Python
python给指定csv表格中的联系人群发邮件(带附件的邮件)
2019/12/31 Python
浅谈numpy中函数resize与reshape,ravel与flatten的区别
2020/06/18 Python
python实现数字炸弹游戏
2020/07/17 Python
HTML5所有标签汇总及标签意义解释
2015/03/12 HTML / CSS
为有想象力的人提供的生活方式商店:Firebox
2018/06/04 全球购物
毕业自我鉴定
2013/11/05 职场文书
小学教育毕业生自荐信
2013/11/18 职场文书
八年级英语教学反思
2014/01/09 职场文书
护理专业自我鉴定
2014/01/30 职场文书
服务口号大全
2014/06/11 职场文书
入党积极分子自我批评思想汇报
2014/10/10 职场文书
党课主持词大全
2015/06/30 职场文书
用Python创建简易网站图文教程
2021/06/11 Python
python之基数排序的实现
2021/07/26 Python