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 获取et和excel的版本号
Apr 09 Python
Python获取电脑硬件信息及状态的实现方法
Aug 29 Python
Python队列的定义与使用方法示例
Jun 24 Python
详解Python下ftp上传文件linux服务器
Jun 21 Python
python 将列表中的字符串连接成一个长路径的方法
Oct 23 Python
python用post访问restful服务接口的方法
Dec 07 Python
python利用tkinter实现屏保
Jul 30 Python
python PIL和CV对 图片的读取,显示,裁剪,保存实现方法
Aug 07 Python
python实现按首字母分类查找功能
Oct 31 Python
PyTorch 随机数生成占用 CPU 过高的解决方法
Jan 13 Python
简单了解python调用其他脚本方法实例
Mar 26 Python
基于Python和C++实现删除链表的节点
Jul 06 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实现encode64编码类实例
2015/03/24 PHP
PHP之将POST数据转化为字符串的实现代码
2016/11/03 PHP
PHP对象实例化单例方法
2017/01/19 PHP
PHP封装返回Ajax字符串和JSON数组的方法
2017/02/17 PHP
Javascript 原型和继承(Prototypes and Inheritance)
2009/04/01 Javascript
浅谈JavaScript的Polymer框架中的事件绑定
2015/07/29 Javascript
由浅入深讲解Javascript继承机制与simple-inheritance源码分析
2015/12/13 Javascript
JS简单循环遍历json数组的方法
2016/04/22 Javascript
javascript添加前置0(补零)的几种方法
2017/01/05 Javascript
vue实现点击关注后及时更新列表功能
2018/06/26 Javascript
详解搭建es6+devServer简单开发环境
2018/09/25 Javascript
如何在Angular应用中创建包含组件方法示例
2019/03/23 Javascript
小程序实现多个选项卡切换
2020/06/19 Javascript
详解Django中的form库的使用
2015/07/18 Python
Python中创建字典的几种方法总结(推荐)
2017/04/27 Python
python生成词云的实现方法(推荐)
2017/06/13 Python
Python实现文件内容批量追加的方法示例
2017/08/29 Python
放弃 Python 转向 Go语言有人给出了 9 大理由
2017/10/20 Python
tensorflow 获取模型所有参数总和数量的方法
2018/06/14 Python
Django项目创建到启动详解(最全最详细)
2019/09/07 Python
python对Excel按条件进行内容补充(推荐)
2019/11/24 Python
解决pytorch-yolov3 train 报错的问题
2020/02/18 Python
Python连接mysql数据库及简单增删改查操作示例代码
2020/08/03 Python
纯css3制作网站后台管理面板
2014/12/30 HTML / CSS
详解CSS3中Media Queries的相关使用
2015/07/17 HTML / CSS
美国床垫连锁店:Mattress Firm
2021/02/13 全球购物
副护士长竞聘演讲稿
2014/04/30 职场文书
导师就业推荐信范文
2014/05/22 职场文书
公司领导班子对照检查存在问题整改措施
2014/10/02 职场文书
2014年超市工作总结
2014/11/19 职场文书
学历证明样本
2015/06/16 职场文书
教师个人教学反思
2016/02/23 职场文书
python Tkinter的简单入门教程
2021/04/11 Python
Java多条件判断场景中规则执行器的设计
2021/06/26 Java/Android
Linux中如何安装并部署Redis
2022/04/18 Servers
SQL Server使用CROSS APPLY与OUTER APPLY实现连接查询
2022/05/25 SQL Server