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中表达式i += x与i = i + x是否等价
Feb 08 Python
[原创]python爬虫(入门教程、视频教程)
Jan 08 Python
Python 函数list&amp;read&amp;seek详解
Aug 28 Python
python同时替换多个字符串方法示例
Sep 17 Python
Python3+Requests+Excel完整接口自动化测试框架的实现
Oct 11 Python
Pygame的程序开始示例代码
May 07 Python
python3.6环境下安装freetype库和基本使用方法(推荐)
May 10 Python
Pandas实现一列数据分隔为两列
May 18 Python
Python3 Tensorlfow:增加或者减小矩阵维度的实现
May 22 Python
Biblibili视频投稿接口分析并以Python实现自动投稿功能
Feb 05 Python
Python机器学习实战之k-近邻算法的实现
Nov 27 Python
python使用pycharm安装pyqt5以及相关配置
Apr 22 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
PHP4实际应用经验篇(7)
2006/10/09 PHP
php中的观察者模式
2010/03/24 PHP
php 获取一个月第一天与最后一天的代码
2010/05/16 PHP
如何解决PHP无法实现多线程的问题
2015/09/25 PHP
php微信公众号开发之欢迎老朋友
2018/10/20 PHP
Vagrant(WSL)+PHPStorm+Xdebu 断点调试环境搭建
2019/12/13 PHP
飞鱼(shqlsl) javascript作品集
2006/12/16 Javascript
Javascript学习笔记之函数篇(六) : 作用域与命名空间
2014/11/23 Javascript
nodejs实现HTTPS发起POST请求
2015/04/23 NodeJs
轻松学习jQuery插件EasyUI EasyUI创建树形菜单
2015/11/30 Javascript
自学实现angularjs依赖注入
2016/12/20 Javascript
js中数组的常用方法小结
2016/12/30 Javascript
vue日期组件 支持vue1.0和2.0
2017/01/09 Javascript
微信小程序媒体组件详解(视频,音乐,图片)
2017/09/19 Javascript
原生js实现省市区三级联动代码分享
2018/02/12 Javascript
利用vue和element-ui设置表格内容分页的实例
2018/03/02 Javascript
layuiAdmin循环遍历展示商品图片列表的方法
2019/09/16 Javascript
Vue优化:常见会导致内存泄漏问题及优化详解
2020/08/04 Javascript
Javascript实现打鼓效果
2021/01/29 Javascript
利用python 更新ssh 远程代码 操作远程服务器的实现代码
2018/02/08 Python
Tensorflow之Saver的用法详解
2018/04/23 Python
python字符串常用方法
2018/06/14 Python
Python企业编码生成系统之系统主要函数设计详解
2019/07/26 Python
Python爬取智联招聘数据分析师岗位相关信息的方法
2019/08/13 Python
Python包,__init__.py功能与用法分析
2020/01/07 Python
css3 box-shadow阴影(外阴影与外发光)图示讲解
2017/08/11 HTML / CSS
英国最大的电脑零售连锁店集团:PC World
2016/10/10 全球购物
2014自荐信的写作技巧
2014/01/28 职场文书
教师自我鉴定范文
2014/03/20 职场文书
司法所长先进事迹
2014/06/02 职场文书
2014单位领导班子四风对照检查材料思想汇报
2014/09/25 职场文书
十八大宣传标语
2014/10/09 职场文书
2014年乡镇卫生院工作总结
2014/11/24 职场文书
Python 中的单分派泛函数你真的了解吗
2021/06/22 Python
HTML实现仿Windows桌面主题特效的实现
2022/06/28 HTML / CSS
Nginx 502 bad gateway错误解决的九种方案及原因
2022/08/14 Servers