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的汉字转GBK码实现代码
Feb 19 Python
python脚本内运行linux命令的方法
Jul 02 Python
使用Django的模版来配合字符串翻译工作
Jul 27 Python
Python smtplib实现发送邮件功能
May 22 Python
python实现图片转字符小工具
Apr 30 Python
python pytest进阶之xunit fixture详解
Jun 27 Python
python tkinter库实现气泡屏保和锁屏
Jul 29 Python
Python综合应用名片管理系统案例详解
Jan 03 Python
Python各种扩展名区别点整理
Feb 27 Python
使用keras实现densenet和Xception的模型融合
May 23 Python
利用Python的folium包绘制城市道路图的实现示例
Aug 24 Python
Python+Appium实现自动化清理微信僵尸好友的方法
Feb 04 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
apache mysql php 源码编译使用方法
2012/05/03 PHP
基于php-fpm 参数的深入理解
2013/06/03 PHP
浅谈Javascript 执行顺序
2013/12/18 Javascript
jquery取消选择select下拉框示例代码
2014/02/22 Javascript
JavaScript实现数字数组正序排列的方法
2015/04/06 Javascript
js实现类似菜单风格的TAB选项卡效果代码
2015/08/28 Javascript
静态页面html中跳转传值的JS处理技巧
2016/06/22 Javascript
vue动态组件实现选项卡切换效果
2017/03/08 Javascript
使用 Vue.js 仿百度搜索框的实例代码
2017/05/09 Javascript
利用canvas实现的加载动画效果实例代码
2017/07/05 Javascript
Vue.js devtool插件安装后无法使用的解决办法
2017/11/27 Javascript
vue 系列——vue2-webpack2框架搭建踩坑之路
2017/12/22 Javascript
深入学习TypeScript 、React、 Redux和Ant-Design的最佳实践
2019/06/17 Javascript
Vue实现购物车详情页面的方法
2019/08/20 Javascript
vue:el-input输入时限制输入的类型操作
2020/08/05 Javascript
JavaScript浅层克隆与深度克隆示例详解
2020/09/01 Javascript
[02:20]DOTA2英雄基础教程 黑暗贤者
2013/12/19 DOTA
用Python中的__slots__缓存资源以节省内存开销的方法
2015/04/02 Python
Python AES加密模块用法分析
2017/05/22 Python
python生成二维码的实例详解
2017/10/29 Python
python随机数分布random测试
2018/08/27 Python
python 获得任意路径下的文件及其根目录的方法
2019/02/16 Python
python多线程并发让两个LED同时亮的方法
2019/02/18 Python
Django项目之Elasticsearch搜索引擎的实例
2019/08/21 Python
Python实现生成密码字典的方法示例
2019/09/02 Python
TensorFlow2.1.0安装过程中setuptools、wrapt等相关错误指南
2020/04/08 Python
pycharm 对代码做静态检查操作
2020/06/09 Python
Python使用struct处理二进制(pack和unpack用法)
2020/11/12 Python
css3中的calc函数浅析
2018/07/10 HTML / CSS
详解HTML5表单新增属性
2016/12/21 HTML / CSS
html5表单及新增的改良元素详解
2016/06/07 HTML / CSS
Diptyque英国官方网站:源自法国的知名香氛品牌
2019/08/28 全球购物
扩大国家免疫规划实施方案
2014/03/21 职场文书
运动会5000米加油稿
2015/07/21 职场文书
蔬果开业典礼发言稿应该怎么写?
2019/09/03 职场文书
Python OpenCV实现图像模板匹配详解
2022/04/07 Python