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面向对象编程中类的继承
Jun 17 Python
matplotlib绘制动画代码示例
Jan 02 Python
Odoo中如何生成唯一不重复的序列号详解
Feb 10 Python
详解python中的线程
Feb 10 Python
基于python 二维数组及画图的实例详解
Apr 03 Python
Python利用openpyxl库遍历Sheet的实例
May 03 Python
Python使用pydub库对mp3与wav格式进行互转的方法
Jan 10 Python
详解python中的数据类型和控制流
Aug 08 Python
python中的线程threading.Thread()使用详解
Dec 17 Python
解决使用Pandas 读取超过65536行的Excel文件问题
Nov 10 Python
python利用pytesseract 实现本地识别图片文字
Dec 14 Python
Python OpenCV实现图形检测示例详解
Apr 08 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中一些字符串总结
2016/05/05 PHP
Thinkphp批量更新数据的方法汇总
2016/06/29 PHP
jquery的Tooltip插件 qtip使用详细说明
2010/09/08 Javascript
深入理解JavaScript系列(50):Function模式(下篇)
2015/03/04 Javascript
JavaScript对HTML DOM使用EventListener进行操作
2015/10/21 Javascript
BootStrap无限级分类(无限极分类封装版)
2016/08/26 Javascript
angular 动态组件类型详解(四种组件类型)
2017/02/22 Javascript
JavaScript实现弹窗效果代码分析
2017/03/09 Javascript
JS实现自定义状态栏动画文字效果示例
2017/10/12 Javascript
bootstrap table支持高度百分比的实例代码
2018/02/28 Javascript
js动态添加带圆圈序号列表的实例代码
2021/02/18 Javascript
Python升级提示Tkinter模块找不到的解决方法
2014/08/22 Python
在Windows服务器下用Apache和mod_wsgi配置Python应用的教程
2015/05/06 Python
Python程序中用csv模块来操作csv文件的基本使用教程
2016/03/03 Python
python+numpy+matplotalib实现梯度下降法
2018/08/31 Python
对Python中的条件判断、循环以及循环的终止方法详解
2019/02/08 Python
python 定时器,轮询定时器的实例
2019/02/20 Python
应用OpenCV和Python进行SIFT算法的实现详解
2019/08/21 Python
python飞机大战pygame碰撞检测实现方法分析
2019/12/17 Python
Python模块/包/库安装的六种方法及区别
2020/02/24 Python
使用分层画布来优化HTML5渲染的教程
2015/05/08 HTML / CSS
html5中audio支持音频格式的解决方法
2018/08/24 HTML / CSS
美国尼曼百货官网:Neiman Marcus
2019/09/05 全球购物
Java和Javasciprt的区别
2012/09/02 面试题
描述内存分配方式以及它们的区别
2016/10/15 面试题
自荐书模板
2013/12/15 职场文书
家长给孩子的表扬信
2014/01/17 职场文书
优秀信贷员先进事迹
2014/01/31 职场文书
电子信息工程专业推荐信
2014/02/14 职场文书
2014迎新年晚会策划方案
2014/02/23 职场文书
绘画专业自荐信
2014/07/04 职场文书
有限责任公司股东合作协议书范本
2014/10/30 职场文书
2015年效能监察工作总结
2015/04/23 职场文书
大学生志愿者心得体会
2016/01/15 职场文书
2019入党申请书格式
2019/06/25 职场文书
python单元测试之pytest的使用
2021/06/07 Python