xml地图|网站地图|网站标签 [设为首页] [加入收藏]

发送文件的实例代码,基于python3实现socket文件传

来源:http://www.ccidsi.com 作者:集成介绍 人气:109 发布时间:2019-06-05
摘要:目录结构: 依据socket的文件传输并进行MD伍值校验,供我们参考,具体内容如下 文件传输分为多个类,三个是服务端,2个是客户端。 client: 客户端发起发送文书或收取文件的央浼,服

目录结构:

依据socket的文件传输并进行MD伍值校验,供我们参考,具体内容如下

图片 1

文件传输分为多个类,三个是服务端,2个是客户端。

client:

客户端发起发送文书或收取文件的央浼,服务端收到请求后收到或发送文书,最后进行MD伍值的校验

#!/usr/bin/env python
# -*-coding:utf-8 -*-
import socket, struct, json
download_dir = r'D:Pythonpython_learninggdcodepart3\02网络编程文件传输clientdownload'
gd_client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
gd_client.connect(('127.0.0.1',8123))

socket数据经过struct模块打包

while True:

内需发送文书到服务端时,调用sendFile函数,struct包内富含文件音信、文件大小、文件MD5等音信,服务端接收到文件后展开MD五值校验,校验成功后则赶回成功

 #1、发命令
  cmd=input('>>: ').strip() #get a.txt
  if not cmd:continue
  gd_client.send(cmd.encode('utf-8'))
  #2、以写的方式打开一个新文件,接收服务端发来的文件的内容写入客户的新文件
  #第一步:先收报头的长度
  obj=gd_client.recv(4)
  header_size=struct.unpack('i',obj)[0]
  # 第二步:再收报头
  header_bytes = gd_client.recv(header_size)
  # 第三步:从报头中解析出对真实数据的描述信息
  header_json = header_bytes.decode('utf-8')
  header_dic = json.loads(header_json)
  '''
  header_dic = {
    'filename': filename, # 1.txt
    'file_size': os.path.getsize(r'%s%s' % (share_dir, filename)) # 路径/1.txt
  }  
  '''
  total_size = header_dic['file_size']
  file_name = header_dic['filename']
  # 第四步:接收真实的数据
  with open(r'%s%s'%(download_dir, file_name),'wb') as f:
    recv_size = 0
    while recv_size < total_size:
      line = gd_client.recv(1024)
      f.write(line)
      recv_size  = len(line)
      print('总大小:%s  已下载大小:%s' % (total_size, recv_size))
gd_client.close()​

须求从服务器下载文件时,调用recvFile函数,收到文件后张开MD5校验

server:

client类代码如下

#!/usr/bin/env python
# -*-coding:utf-8 -*-
import socket
import subprocess
import struct
import json
import os
share_dir = r'D:Pythonpython_learninggdcodepart3\02网络编程文件传输servershare'
gd_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
gd_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
gd_server.bind(('127.0.0.1', 8123)) # 0-65535: 0-1024给操作系统使用
gd_server.listen(5)
while True:
  conn, client_addr = gd_server.accept()
  while True: # 通信循环
    try:
      # 1、收命令
      res = conn.recv(8096) # b'get 1.txt'
      if not res: break # 适用于linux操作系统
      # 2、解析命令,提取相应命令参数
      cmds = res.decode('utf-8').split() # ['get','1.txt']
      filename = cmds[1]
      # 3、以读的方式打开文件,读取文件内容发送给客户端
      # 第一步:制作固定长度的报头
      header_dic = {
        'filename': filename, # 1.txt
        'file_size':os.path.getsize(r'%s%s'%(share_dir, filename)) # 路径/1.txt
      }
      header_json = json.dumps(header_dic)
      header_bytes = header_json.encode('utf-8')
      # 第二步:先发送报头的长度
      conn.send(struct.pack('i',len(header_bytes)))
      # 第三步:再发报头
      conn.send(header_bytes)
      # 第四步:再发送真实的数据
      with open('%s/%s'%(share_dir, filename),'rb') as f:
        for line in f:
          conn.send(line)
    except ConnectionResetError: # 适用于windows操作系统
      break
  conn.close()
gd_server.close()​
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)

本文由68399皇家赌场发布于集成介绍,转载请注明出处:发送文件的实例代码,基于python3实现socket文件传

关键词: 68399皇家赌场

最火资讯