基于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中的五种异常处理机制介绍
Sep 02 Python
在Python中使用全局日志时需要注意的问题
May 06 Python
Python根据区号生成手机号码的方法
Jul 08 Python
解决pandas read_csv 读取中文列标题文件报错的问题
Jun 15 Python
python 找出list中最大或者最小几个数的索引方法
Oct 30 Python
利用python提取wav文件的mfcc方法
Jan 09 Python
实例详解Python模块decimal
Jun 26 Python
python3将变量写入SQL语句的实现方式
Mar 02 Python
Python读入mnist二进制图像文件并显示实例
Apr 24 Python
基于python检查矩阵计算结果
May 21 Python
Pandas之缺失数据的实现
Jan 06 Python
利用Python如何画一颗心、小人发射爱心
Feb 21 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
德劲1104的电路分析与改良
2021/03/01 无线电
无线电广播与收音机发展的历史回眸
2021/03/02 无线电
php 什么是PEAR?(第三篇)
2009/03/19 PHP
php使用指定编码导出mysql数据到csv文件的方法
2015/03/31 PHP
PHP基于socket实现客户端和服务端通讯功能
2017/07/13 PHP
PHP使用Redis实现防止大并发下二次写入的方法
2017/10/09 PHP
JavaScript实现多维数组的方法
2013/11/20 Javascript
如何使用Bootstrap的modal组件自定义alert,confirm和modal对话框
2016/03/01 Javascript
利用jquery给指定的table动态添加一行、删除一行的方法
2016/10/12 Javascript
bootstrap侧边栏圆点导航
2017/01/11 Javascript
基于jQuery制作小图标上下滑动特效
2017/01/18 Javascript
深入理解Promise.all
2018/08/08 Javascript
如何实现一个webpack模块解析器
2018/10/24 Javascript
JavaScript ES6箭头函数使用指南
2018/12/30 Javascript
详解vue-cli项目开发/生产环境代理实现跨域请求
2019/07/23 Javascript
Paypal支付不完全指北
2020/06/04 Javascript
bootstrap-closable-tab可实现关闭的tab标签页插件
2020/08/09 Javascript
在Python的Django框架中包装视图函数
2015/07/20 Python
讲解Python的Scrapy爬虫框架使用代理进行采集的方法
2016/02/18 Python
Python开发SQLite3数据库相关操作详解【连接,查询,插入,更新,删除,关闭等】
2017/07/27 Python
自定义django admin model表单提交的例子
2019/08/23 Python
OpenCV Python实现拼图小游戏
2020/03/23 Python
如何使用Python进行PDF图片识别OCR
2021/01/22 Python
欧洲第一中国智能手机和平板电脑网上商店:CECT-SHOP
2018/01/08 全球购物
英国最受欢迎的母婴精品品牌:JoJo Maman BéBé
2021/02/17 全球购物
如何高效率的查找一个月以内的数据
2012/04/15 面试题
事业单位请假制度
2014/01/13 职场文书
志愿者服务感言
2014/02/27 职场文书
计算机应用专业自荐信
2014/07/05 职场文书
自主招生学校推荐信
2014/09/26 职场文书
入党转正申请报告
2015/05/15 职场文书
Django使用redis配置缓存的方法
2021/06/01 Redis
java设计模式--原型模式详解
2021/07/21 Java/Android
浅析CSS在DevTools 中架构演变
2021/10/05 HTML / CSS
《传颂之物 虚伪的假面》BD发售宣传CM公开
2022/04/04 日漫
muduo TcpServer模块源码分析
2022/04/26 Redis