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解释器理解Python中的字节码
Apr 01 Python
Python中使用strip()方法删除字符串中空格的教程
May 20 Python
python解决Fedora解压zip时中文乱码的方法
Sep 18 Python
Python自定义线程类简单示例
Mar 23 Python
实例讲解Python中浮点型的基本内容
Feb 11 Python
Python递归函数 二分查找算法实现解析
Aug 12 Python
关于pytorch中网络loss传播和参数更新的理解
Aug 20 Python
Python2比较当前图片跟图库哪个图片相似的方法示例
Sep 28 Python
python pyecharts 实现一个文件绘制多张图
May 13 Python
python怎么提高计算速度
Jun 11 Python
Python 必须了解的5种高级特征
Sep 10 Python
python pygame 开发五子棋双人对弈
May 02 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
Windows7下PHP开发环境安装配置图文方法
2010/05/20 PHP
php 获取本地IP代码
2013/06/23 PHP
PHP中的流(streams)浅析
2015/07/02 PHP
详解WordPress开发中用于获取分类及子页面的函数用法
2016/01/08 PHP
PHP程序中的文件锁、互斥锁、读写锁使用技巧解析
2016/03/21 PHP
JsEasy简介 JsEasy是什么?与下载
2007/03/07 Javascript
JQery 渐变图片导航效果代码 漂亮
2010/01/01 Javascript
Javascript浅谈之引用类型
2013/12/18 Javascript
JavaScript清空数组元素的两种方法简单比较
2015/07/10 Javascript
javascript中checkbox使用方法实例演示
2015/11/19 Javascript
jQuery实现鼠标双击Table单元格变成文本框及输入内容后更新到数据库的方法
2015/11/25 Javascript
使用JavaScript为Kindeditor自定义按钮增加Audio标签
2016/03/18 Javascript
jQuery控制div实现随滚动条滚动效果
2016/06/07 Javascript
bootstrap滚动监控器使用方法解析
2017/01/13 Javascript
js实现PC端根据IP定位当前城市地理位置
2017/02/22 Javascript
vue使用vue-cli快速创建工程
2017/07/28 Javascript
微信小程序自定义多选事件的实现代码
2018/05/17 Javascript
vue-awesome-swiper 基于vue实现h5滑动翻页效果【推荐】
2018/11/08 Javascript
玩转Koa之核心原理分析
2018/12/29 Javascript
微信小程序配置服务器提示验证token失败的解决方法
2019/04/03 Javascript
vue不操作dom实现图片轮播的示例代码
2019/12/18 Javascript
[52:08]DOTA2上海特级锦标赛主赛事日 - 3 败者组第三轮#2Fnatic VS OG第一局
2016/03/05 DOTA
python操作redis方法总结
2018/06/06 Python
基于Python实现定时自动给微信好友发送天气预报
2018/10/25 Python
python判断文件是否存在,不存在就创建一个的实例
2019/02/18 Python
对Python 简单串口收发GUI界面的实例详解
2019/06/12 Python
pycharm快捷键汇总
2020/02/14 Python
css3实现信纸/同学录效果的示例代码
2018/12/11 HTML / CSS
viagogo法国票务平台:演唱会、体育比赛、戏剧门票
2017/03/27 全球购物
大三预备党员入党思想汇报
2014/01/08 职场文书
学期研究性学习个人的自我评价
2014/01/09 职场文书
成品库仓管员岗位职责
2014/04/06 职场文书
妇女工作先进事迹
2014/08/17 职场文书
校外活动方案
2014/08/28 职场文书
网球场地租赁协议范本
2014/10/07 职场文书
Nginx反向代理学习实例教程
2021/10/24 Servers