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求斐波那契数列示例分享
Feb 14 Python
python3学习笔记之多进程分布式小例子
Feb 13 Python
Python实现k-means算法
Feb 23 Python
python删除不需要的python文件方法
Apr 24 Python
python处理multipart/form-data的请求方法
Dec 26 Python
Python实现的爬取百度贴吧图片功能完整示例
May 10 Python
Django 使用easy_thumbnails压缩上传的图片方法
Jul 26 Python
tensorflow模型保存、加载之变量重命名实例
Jan 21 Python
Tensorflow进行多维矩阵的拆分与拼接实例
Feb 07 Python
Tensorflow 实现将图像与标签数据转化为tfRecord文件
Feb 17 Python
python 实现性别识别
Nov 21 Python
python中的sys模块和os模块
Mar 20 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 iconv函数的使用详解
2013/06/09 PHP
php+mysql实现用户注册登陆的方法
2015/01/03 PHP
PHP实现非阻塞模式的方法分析
2018/07/26 PHP
laravel 5.5 关闭token的3种实现方式
2019/10/24 PHP
php利用ZipArchive类操作文件的实例
2020/01/21 PHP
jquery photoFrame 图片边框美化显示插件
2010/06/28 Javascript
基于jquery的固定表头和列头的代码
2012/05/03 Javascript
javascript模拟地球旋转效果代码实例
2013/12/02 Javascript
js获取select选中的option的text示例代码
2013/12/19 Javascript
Javascript 拖拽的一些简单的应用(逐行分析代码,让你轻松了拖拽的原理)
2015/01/23 Javascript
JS实现下拉菜单赋值到文本框的方法
2015/08/18 Javascript
实例解析JS布尔对象的toString()方法和valueOf()方法
2015/10/25 Javascript
详解Document.Cookie
2015/12/25 Javascript
浏览器检测JS代码(兼容目前各大主流浏览器)
2016/02/21 Javascript
JavaScript的Ext JS框架中的GridPanel组件使用指南
2016/05/21 Javascript
Jquery通过ajax请求NodeJS返回json数据实例
2016/11/08 NodeJs
jQuery实现的浮动层div浏览器居中显示效果
2017/02/03 Javascript
Vue.js路由vue-router使用方法详解
2017/03/20 Javascript
JS实现异步上传压缩图片
2017/04/22 Javascript
手挽手带你学React之React-router4.x的使用
2019/02/14 Javascript
js打开word文档预览操作示例【不是下载】
2019/05/23 Javascript
Node登录权限验证token验证实现的方法示例
2020/05/25 Javascript
[01:10:58]KG vs TNC 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/16 DOTA
python3.3使用tkinter开发猜数字游戏示例
2014/03/14 Python
Python标准库之多进程(multiprocessing包)介绍
2014/11/25 Python
Python中numpy模块常见用法demo实例小结
2019/03/16 Python
Python如何用filter函数筛选数据
2020/03/05 Python
python实现mean-shift聚类算法
2020/06/10 Python
恶意软件的定义
2014/11/12 面试题
如何进行Linux分区优化
2013/02/12 面试题
应届生体育教师自荐信
2013/10/03 职场文书
《月球之谜》教学反思
2014/04/10 职场文书
幼儿发展评估方案
2014/06/11 职场文书
车辆管理制度范本
2015/08/05 职场文书
趣味运动会标语口号
2015/12/26 职场文书
关于职业道德的心得体会
2016/01/18 职场文书