python单线程文件传输的实例(C/S)


Posted in Python onFebruary 13, 2019

客户端代码:

#-*-encoding:utf-8-*-
 
import socket
import os
import sys
import math
import time
 
def progressbar(cur, total):
 percent = '{:.2%}'.format(float(cur) / float(total))
 sys.stdout.write('\r')
 sys.stdout.write("[%-50s] %s" % (
       '=' * int(math.floor(cur * 50 / total)),
       percent))
 sys.stdout.flush()
 
def getFileSize(file):
 file.seek(0, os.SEEK_END)
 fileLength = file.tell()
 file.seek(0, 0)
 return fileLength
 
def getFileName(fileFullPath):
 index = fileFullPath.rindex('\\')
 if index == -1:
  return fileFullPath 
 else:
  return fileFullPath[index+1:]
 
def transferFile():
 fileFullPath = r"%s" % raw_input("File path: ").strip("\"")
 if os.path.exists(fileFullPath):
  timeStart = time.clock()
  file = open(fileFullPath, 'rb')
  fileSize = getFileSize(file)
  client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  client.connect((targetHost, targetPort))
  # send file size
  client.send(str(fileSize))
  response = client.recv(1024)
  # send file name
  client.send(getFileName(fileFullPath))
  response = client.recv(1024)
  # send file content
  sentLength = 0
  while sentLength < fileSize:
   bufLen = 1024
   buf = file.read(bufLen)
   client.send(buf)
   sentLength += len(buf)
   process = int(float(sentLength) / float(fileSize) * 100)
   progressbar(process, 100)
  client.recv(1024)
  file.close()
  timeEnd = time.clock()
  print "\r\nFinished, spent %d seconds" % (timeEnd - timeStart)
 else:
  print "File doesn't exist"
 
targetHost = raw_input("Server IP Address: ")
targetPort = int(raw_input("Server port: "))
 
while True:
 transferFile()

服务器端代码:

#-*-encoding:utf-8-*-
 
import socket
import threading
import os
import sys
import math
 
bindIp = "0.0.0.0"
bindPort = 9999
 
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bindIp, bindPort))
server.listen(1)
print "Listening on %s:%d" % (bindIp, bindPort)
 
def progressbar(cur, total):
 percent = '{:.2%}'.format(float(cur) / float(total))
 sys.stdout.write('\r')
 sys.stdout.write("[%-50s] %s" % (
       '=' * int(math.floor(cur * 50 / total)),
       percent))
 sys.stdout.flush()
 
def checkFileName(originalFileName):
 extensionIndex = originalFileName.rindex(".")
 name = originalFileName[:extensionIndex]
 extension = originalFileName[extensionIndex+1:]
 
 index = 1
 newNameSuffix = "(" + str(index) + ")"
 finalFileName = originalFileName
 if os.path.exists(finalFileName):
  finalFileName = name + " " + newNameSuffix + "." + extension
 while os.path.exists(finalFileName):
  index += 1
  oldSuffix = newNameSuffix
  newNameSuffix = "(" + str(index) + ")"
  finalFileName = finalFileName.replace(oldSuffix, newNameSuffix)
 return finalFileName
 
def handleClient(clientSocket):
 # receive file size
 fileSize = int(clientSocket.recv(1024))
 # print "[<==] File size received from client: %d" % fileSize
 clientSocket.send("Received")
 # receive file name
 fileName = clientSocket.recv(1024)
 # print "[<==] File name received from client: %s" % fileName
 clientSocket.send("Received")
 fileName = checkFileName(fileName)
 file = open(fileName, 'wb')
 # receive file content
 print "[==>] Saving file to %s" % fileName
 receivedLength = 0
 while receivedLength < fileSize:
  bufLen = 1024
  if fileSize - receivedLength < bufLen:
   bufLen = fileSize - receivedLength
  buf = clientSocket.recv(bufLen)
  file.write(buf)
  receivedLength += len(buf)
  process = int(float(receivedLength) / float(fileSize) * 100)
  progressbar(process, 100)
 
 file.close()
 print "\r\n[==>] File %s saved." % fileName
 clientSocket.send("Received")
 
while True:
 client, addr = server.accept()
 print "[*] Accepted connection from: %s:%d" % (addr[0], addr[1])
 
 clientHandler = threading.Thread(target=handleClient, args=(client,))
 clientHandler.start()

运行结果示例:

服务器端:

python单线程文件传输的实例(C/S)

客户端(服务器端做了端口映射:59999->9999):

python单线程文件传输的实例(C/S)

以上这篇python单线程文件传输的实例(C/S)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python配置文件解析模块ConfigParser使用实例
Apr 13 Python
Python设计模式中单例模式的实现及在Tornado中的应用
Mar 02 Python
python re模块的高级用法详解
Jun 06 Python
Pandas 同元素多列去重的实例
Jul 03 Python
详解Python匿名函数(lambda函数)
Apr 19 Python
python Tkinter的图片刷新实例
Jun 14 Python
Python 最强编辑器详细使用指南(PyCharm )
Sep 16 Python
解决pyCharm中 module 调用失败的问题
Feb 12 Python
Django使用rest_framework写出API
May 21 Python
Python smtp邮件发送模块用法教程
Jun 15 Python
Python如何给你的程序做性能测试
Jul 29 Python
python基础之while循环语句的使用
Apr 20 Python
Python 实现文件打包、上传与校验的方法
Feb 13 #Python
使用python3构建文件传输的方法
Feb 13 #Python
对python 自定义协议的方法详解
Feb 13 #Python
Python 实现两个服务器之间文件的上传方法
Feb 13 #Python
Python魔法方法详解
Feb 13 #Python
Python函数中不定长参数的写法
Feb 13 #Python
python调用c++ ctype list传数组或者返回数组的方法
Feb 13 #Python
You might like
php 定界符格式引起的错误
2011/05/24 PHP
PHP递归复制、移动目录的自定义函数分享
2014/11/18 PHP
php获取字符串中各个字符出现次数的方法
2015/02/23 PHP
PHP7 新增功能
2021/03/09 PHP
JQuery 学习笔记 选择器之四
2009/07/23 Javascript
jquery操作cookie插件分享
2014/01/14 Javascript
JavaScript中的包装对象介绍
2015/01/27 Javascript
利用js定义一个导航条菜单
2017/03/14 Javascript
vue.js 初体验之Chrome 插件开发实录
2017/05/13 Javascript
浅谈react+es6+webpack的基础配置
2017/08/09 Javascript
在vue中,v-for的索引index在html中的使用方法
2018/03/06 Javascript
原生JS实现的轮播图功能详解
2018/08/06 Javascript
Electron中实现大文件上传和断点续传功能
2018/10/28 Javascript
爬虫利器Puppeteer实战
2019/01/09 Javascript
JavaScript 防盗链的原理以及破解方法
2020/12/29 Javascript
在Python中操作时间之strptime()方法的使用
2020/12/30 Python
用Eclipse写python程序
2018/02/10 Python
人脸识别经典算法一 特征脸方法(Eigenface)
2018/03/13 Python
PyQt5每天必学之像素图控件QPixmap
2018/04/19 Python
OpenCV 边缘检测
2019/07/10 Python
python做接口测试的必要性
2019/11/20 Python
numpy np.newaxis 的实用分享
2019/11/30 Python
python argparse模块通过后台传递参数实例
2020/04/20 Python
python实现四人制扑克牌游戏
2020/04/22 Python
解决pyinstaller 打包exe文件太大,用pipenv 缩小exe的问题
2020/07/13 Python
python 三种方法实现对Excel表格的读写
2020/11/19 Python
Hawes & Curtis澳大利亚官网:英国经典服饰品牌
2018/10/29 全球购物
大学生职业生涯规划范文
2013/12/31 职场文书
自立自强的名人事例
2014/02/10 职场文书
人民教师的自我评价分享
2014/02/21 职场文书
人力资源管理专业应届生求职信
2014/04/24 职场文书
住院医师规范化培训实施方案
2014/06/12 职场文书
党委班子剖析材料
2014/08/21 职场文书
幼师自荐信范文
2015/03/06 职场文书
物业接待员岗位职责
2015/04/15 职场文书
Nginx访问日志及错误日志参数说明
2021/03/31 Servers