基于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实现的一个找零钱的小程序代码分享
Aug 25 Python
Python 探针的实现原理
Apr 23 Python
Python写的一个定时重跑获取数据库数据
Dec 28 Python
python opencv实现图像边缘检测
Apr 29 Python
python字符串Intern机制详解
Jul 01 Python
Django缓存系统实现过程解析
Aug 02 Python
nginx黑名单和django限速,最简单的防恶意请求方法分享
Aug 09 Python
在macOS上搭建python环境的实现方法
Aug 13 Python
pyCharm 实现关闭代码检查
Jun 09 Python
怎么快速自学python
Jun 22 Python
基于Python采集爬取微信公众号历史数据
Nov 27 Python
python lambda的使用详解
Feb 26 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
评分9.0以上的动画电影,剧情除了经典还很燃
2020/03/04 日漫
全国FM电台频率大全 - 10 江苏省
2020/03/11 无线电
一个程序下载的管理程序(三)
2006/10/09 PHP
PHP学习之字符串比较和查找
2011/04/17 PHP
PHP数据类型之布尔型的介绍
2013/04/28 PHP
php代码审计比较有意思的例子
2014/05/07 PHP
php根据生日计算年龄的方法
2015/07/13 PHP
PHP随手笔记整理之PHP脚本和JAVA连接mysql数据库
2015/11/25 PHP
php接口实现拖拽排序功能
2018/04/23 PHP
PHP实现的策略模式示例
2019/03/20 PHP
javascript jQuery $.post $.ajax用法
2008/07/09 Javascript
javascript模拟评分控件实现方法
2015/05/13 Javascript
js拖拽的原型声明和用法总结
2016/04/04 Javascript
BootStrap中按钮点击后被禁用按钮的最佳实现方法
2016/09/23 Javascript
Vue.js创建Calendar日历效果
2016/11/03 Javascript
图片懒加载插件实例分享(含解析)
2017/01/09 Javascript
JS百度地图搜索悬浮窗功能
2017/01/12 Javascript
JS设置手机验证码60s等待实现代码
2017/06/14 Javascript
jQuery plugin animsition使用小结
2017/09/14 jQuery
vue2.x+webpack快速搭建前端项目框架详解
2017/11/30 Javascript
jQuery.extend 与 jQuery.fn.extend的用法及区别实例分析
2018/07/25 jQuery
小程序实现投票进度条
2019/11/20 Javascript
electron踩坑之dialog中的callback解决
2020/10/06 Javascript
二种python发送邮件实例讲解(python发邮件附件可以使用email模块实现)
2013/12/03 Python
11月编程语言排行榜 Python逆袭C#上升到第4
2017/11/15 Python
python中format()函数的简单使用教程
2018/03/14 Python
Pycharm保存不能自动同步到远程服务器的解决方法
2019/06/27 Python
Django高并发负载均衡实现原理详解
2020/04/04 Python
python利用opencv实现颜色检测
2021/02/23 Python
使用CSS3来匹配横屏竖屏的简单方法
2015/08/04 HTML / CSS
美国NBA官方商店:NBA Store
2019/04/12 全球购物
程序员经常用到的UNIX命令
2015/04/13 面试题
2014年基层党组织公开承诺书
2014/03/29 职场文书
竞选体育委员演讲稿
2014/04/26 职场文书
高中美术教学反思
2016/02/17 职场文书
使用Spring处理x-www-form-urlencoded方式
2021/11/02 Java/Android