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文本相似性计算之编辑距离详解
Nov 28 Python
Python:Scrapy框架中Item Pipeline组件使用详解
Dec 27 Python
TensorFlow实现MLP多层感知机模型
Mar 09 Python
Python之列表的插入&amp;替换修改方法
Jun 28 Python
python绘制直线的方法
Jun 30 Python
python 实现敏感词过滤的方法
Jan 21 Python
Python告诉你木马程序的键盘记录原理
Feb 02 Python
举例讲解Python常用模块
Mar 08 Python
python里 super类的工作原理详解
Jun 19 Python
tensorflow 初始化未初始化的变量实例
Feb 06 Python
python GUI库图形界面开发之pyinstaller打包python程序为exe安装文件
Feb 26 Python
Pycharm制作搞怪弹窗的实现代码
Feb 19 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
乱谈我对耳机、音箱的感受
2021/03/02 无线电
PHP在线生成二维码代码(google api)
2013/06/03 PHP
PHP示例演示发送邮件给某个邮箱
2019/04/03 PHP
PHP实现随机发扑克牌
2020/04/22 PHP
设置下载不需要倒计时cookie(倒计时代码)
2008/11/19 Javascript
jquery图片延迟加载 前端开发技能必备系列
2012/06/18 Javascript
javascript中的document.open()方法使用介绍
2013/10/09 Javascript
javascript陷阱 一不小心你就中招了(字符运算)
2013/11/10 Javascript
前台js对象在后台转化java对象的问题探讨
2013/12/20 Javascript
js传中文参数controller里获取参数乱码问题解决方法
2014/01/03 Javascript
JavaScript将数组转换成CSV格式的方法
2015/03/19 Javascript
讲解JavaScript中for...in语句的使用方法
2015/06/03 Javascript
JS跨域请求的问题解析
2018/12/03 Javascript
vue页面更新patch的实现示例
2020/03/25 Javascript
vue将data恢复到初始状态 &amp;&amp; 重新渲染组件实例
2020/09/04 Javascript
微信小程序实现首页弹出广告
2020/12/03 Javascript
使用原生javascript开发计算器实例代码
2021/02/21 Javascript
python实现自动登录人人网并访问最近来访者实例
2014/09/26 Python
Python 函数基础知识汇总
2018/03/09 Python
python3获取两个日期之间所有日期,以及比较大小的实例
2018/04/08 Python
Python FTP两个文件夹间的同步实例代码
2018/05/25 Python
python发送告警邮件脚本
2018/09/17 Python
Python 实现Windows开机运行某软件的方法
2018/10/14 Python
Python3中编码与解码之Unicode与bytes的讲解
2019/02/28 Python
使用jupyter Nodebook查看函数或方法的参数以及使用情况
2020/04/14 Python
Python使用OpenPyXL处理Excel表格
2020/07/02 Python
详解Django中异步任务之django-celery
2020/11/05 Python
英文自荐信
2013/12/15 职场文书
事务机电主管工作职责
2014/02/25 职场文书
2014年三万活动总结
2014/04/26 职场文书
农业开发项目建议书
2014/05/16 职场文书
护理专业自荐书
2014/06/04 职场文书
乡镇群众路线专项整治方案
2014/11/03 职场文书
2014年人力资源部工作总结
2014/11/19 职场文书
铁人观后感
2015/06/16 职场文书
教师培训简讯
2015/07/20 职场文书