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 文件读写操作实例详解
Mar 12 Python
使用Python3编写抓取网页和只抓网页图片的脚本
Aug 20 Python
详解Python的collections模块中的deque双端队列结构
Jul 07 Python
Python随机生成数据后插入到PostgreSQL
Jul 28 Python
Python 读写文件和file对象的方法(推荐)
Sep 12 Python
numpy使用fromstring创建矩阵的实例
Jun 15 Python
python requests 测试代理ip是否生效
Jul 25 Python
Python模拟自动存取款机的查询、存取款、修改密码等操作
Sep 02 Python
Python实现九宫格式的朋友圈功能内附“马云”朋友圈
May 07 Python
python 变量初始化空列表的例子
Nov 28 Python
关于pycharm 切换 python3.9 报错 ‘HTMLParser‘ object has no attribute ‘unescape‘ 的问题
Nov 24 Python
python用700行代码实现http客户端
Jan 14 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制作新闻系统的思路
2006/10/09 PHP
PHP速成大法
2015/01/30 PHP
CentOS下PHP安装Oracle扩展
2015/02/15 PHP
漂亮的widgets,支持换肤和后期开发新皮肤(2007-4-27已更新1.7alpha)
2007/04/27 Javascript
JavaScript 克隆数组最简单的方法
2009/02/12 Javascript
为JavaScript添加重载函数的辅助方法
2010/07/04 Javascript
jquery图片延迟加载 前端开发技能必备系列
2012/06/18 Javascript
JS常见问题整理(持续更新)
2013/08/06 Javascript
jquery.autocomplete修改实现键盘上下键自动填充示例
2013/11/19 Javascript
jQuery插件imgPreviewQs实现上传图片预览
2016/01/15 Javascript
Sea.JS知识总结
2016/05/05 Javascript
TinyMCE汉化及本地上传图片功能实例详解
2016/05/31 Javascript
jQuery 常见小例汇总
2016/12/14 Javascript
JavaScript实现单击网页任意位置打开新窗口与关闭窗口的方法
2017/09/21 Javascript
vue中组件的过渡动画及实现代码
2018/11/21 Javascript
Python的Django框架可适配的各种数据库介绍
2015/07/15 Python
python搭建微信公众平台
2016/02/09 Python
python实现RSA加密(解密)算法
2016/02/17 Python
Ubuntu下安装PyV8
2016/03/13 Python
python处理按钮消息的实例详解
2017/07/11 Python
Python实现字符串格式化输出的方法详解
2017/09/20 Python
使用python采集脚本之家电子书资源并自动下载到本地的实例脚本
2018/10/23 Python
python 对字典按照value进行排序的方法
2019/05/09 Python
python @classmethod 的使用场合详解
2019/08/23 Python
Python函数参数分类原理详解
2020/05/28 Python
谷歌浏览器小字体处理方案即12px以下字体
2013/12/17 HTML / CSS
新领导上任欢迎词
2014/01/13 职场文书
教育英语专业毕业生的求职信
2014/03/13 职场文书
生日主持词
2014/03/20 职场文书
音乐教师求职信
2014/06/28 职场文书
房屋买卖授权委托书
2014/09/27 职场文书
2014年数学教师工作总结
2014/12/03 职场文书
学生评语集锦
2015/01/04 职场文书
农村党支部承诺书
2015/04/30 职场文书
2016年教师师德师风承诺书
2016/03/25 职场文书
React自定义hook的方法
2022/06/25 Javascript