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 25 Python
Python基于PycURL自动处理cookie的方法
Jul 25 Python
python复制文件到指定目录的实例
Apr 27 Python
Python设计模式之组合模式原理与用法实例分析
Jan 11 Python
Python字典的基本用法实例分析【创建、增加、获取、修改、删除】
Mar 05 Python
pandas DataFrame 交集并集补集的实现
Jun 24 Python
Python 绘制酷炫的三维图步骤详解
Jul 12 Python
Python实现基于SVM的分类器的方法
Jul 19 Python
django数据库自动重连的方法实例
Jul 21 Python
pycharm配置当鼠标悬停时快速提示方法参数
Jul 31 Python
Python类中方法getitem和getattr详解
Aug 30 Python
pycharm如何使用anaconda中的各种包(操作步骤)
Jul 31 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
windows环境下php配置memcache的具体操作步骤
2013/06/09 PHP
php中请求url的五种方法总结
2017/07/13 PHP
firefox下frameset取不到值的解决方法
2010/09/06 Javascript
封装html的select标签的js操作实例
2013/07/02 Javascript
html5 canvas js(数字时钟)实例代码
2013/12/23 Javascript
一个JS函数搞定网页标题(title)闪动效果
2014/05/13 Javascript
JavaScript解析json格式数据简单示例
2014/12/09 Javascript
浅谈Javascript数组索引
2015/07/29 Javascript
利用HTML5的画布Canvas实现刮刮卡效果
2015/09/06 Javascript
javascript中call apply 与 bind方法详解
2016/03/10 Javascript
JavaScript 监控微信浏览器且自带返回按钮时间
2016/11/27 Javascript
实例解析jQuery中如何取消后续执行内容
2016/12/01 Javascript
AngularJS通过ng-route实现基本的路由功能实例详解
2016/12/13 Javascript
JS 设置Cookie 有效期 检测cookie
2017/06/15 Javascript
浅析JS中常用类型转换及运算符表达式
2017/07/23 Javascript
从源码看angular/material2 中 dialog模块的实现方法
2017/10/18 Javascript
JS实现元素上下左右移动效果
2017/10/18 Javascript
localstorage实现带过期时间的缓存功能
2019/06/28 Javascript
js判断浏览器的环境(pc端,移动端,还是微信浏览器)
2020/12/24 Javascript
ESLint 是如何检查 .vue 文件的
2020/11/30 Vue.js
[01:23]2019完美世界全国高校联赛(春季赛)合肥全国总决赛
2019/06/10 DOTA
python实现socket客户端和服务端简单示例
2014/02/24 Python
Python读取图片EXIF信息类库介绍和使用实例
2014/07/10 Python
Python字符串格式化的方法(两种)
2017/09/19 Python
Python 3 实现定义跨模块的全局变量和使用教程
2019/07/07 Python
Python单元测试工具doctest和unittest使用解析
2019/09/02 Python
python中如何设置代码自动提示
2020/07/15 Python
python使用布隆过滤器的实现示例
2020/08/20 Python
h5页面背景图很长要有滚动条滑动效果的实现
2021/01/27 HTML / CSS
学校教师安全责任书
2014/07/23 职场文书
国庆节演讲稿范文2014
2014/09/19 职场文书
2014年药店店长工作总结
2014/11/17 职场文书
图书借阅制度范本
2015/08/06 职场文书
MySQL8.0.18配置多主一从
2021/06/21 MySQL
Python实现科学占卜 让视频自动打码
2022/04/09 Python
css之clearfix的用法深入理解(必看篇)
2023/05/21 HTML / CSS