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的Flask框架中实现分页功能的教程
Apr 20 Python
Hadoop中的Python框架的使用指南
Apr 22 Python
Python用sndhdr模块识别音频格式详解
Jan 11 Python
Python读取Word(.docx)正文信息的方法
Mar 15 Python
python面向对象入门教程之从代码复用开始(一)
Dec 11 Python
Django实现web端tailf日志文件功能及实例详解
Jul 28 Python
python利用dlib获取人脸的68个landmark
Nov 27 Python
tornado+celery的简单使用详解
Dec 21 Python
python梯度下降算法的实现
Feb 24 Python
使用Keras画神经网络准确性图教程
Jun 15 Python
OpenCV实现机器人对物体进行移动跟随的方法实例
Nov 09 Python
Python读取ini配置文件传参的简单示例
Jan 05 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数据采集的详解
2013/06/02 PHP
jQuery 选择器、DOM操作、事件、动画
2010/11/25 Javascript
用JavaScript获取DOM元素位置和尺寸大小的方法
2013/04/12 Javascript
JS中getYear()和getFullYear()区别分析
2014/07/04 Javascript
JavaScript函数详解
2015/02/27 Javascript
Webpack 实现 AngularJS 的延迟加载
2016/03/02 Javascript
JS中dom0级事件和dom2级事件的区别介绍
2016/05/05 Javascript
jQuery实现的分页功能示例
2017/01/22 Javascript
详解JS中的this、apply、call、bind(经典面试题)
2017/09/19 Javascript
JS实现元素上下左右移动效果
2017/10/18 Javascript
微信小程序实战篇之购物车的实现代码示例
2017/11/30 Javascript
JS声明对象时属性名加引号与不加引号的问题及解决方法
2018/02/16 Javascript
Webpack path与publicPath的区别详解
2018/05/03 Javascript
vue循环数组改变点击文字的颜色
2019/10/14 Javascript
[01:27]2014DOTA2展望TI 剑指西雅图IG战队专访
2014/06/30 DOTA
在Django的通用视图中处理Context的方法
2015/07/21 Python
使用python编写监听端
2018/04/12 Python
Python单元测试实例详解
2018/05/25 Python
浅谈python常用程序算法
2019/03/22 Python
python 实现二维列表转置
2019/12/02 Python
Pycharm 2020最新永久激活码(附最新激活码和插件)
2020/09/17 Python
MNIST数据集转化为二维图片的实现示例
2020/01/10 Python
在Mac中PyCharm配置python Anaconda环境过程图解
2020/03/11 Python
使用python-cv2实现视频的分解与合成的示例代码
2020/10/26 Python
python中函数返回多个结果的实例方法
2020/12/16 Python
使用css3绘制出各种几何图形
2016/08/17 HTML / CSS
Wiggle美国:英国骑行、跑步、游泳、铁人三项商店
2018/10/27 全球购物
土木工程专业个人求职信
2013/12/05 职场文书
护士进修自我鉴定
2014/02/07 职场文书
知识竞赛主持词
2014/03/26 职场文书
优秀共产党员先进事迹材料
2014/05/06 职场文书
正风肃纪剖析材料
2014/09/30 职场文书
医德医风自我评价2015
2015/03/03 职场文书
2015学校师德师风工作总结
2015/04/22 职场文书
2016年员工政治思想表现评语
2015/12/02 职场文书
如何用Python搭建gRPC服务
2021/06/30 Python