python单线程文件传输的实例(C/S)
作者:远行的风 发布时间:2023-04-07 22:45:48
标签:python,单线程,文件,传输
客户端代码:
#-*-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()
运行结果示例:
服务器端:
客户端(服务器端做了端口映射:59999->9999):
来源:https://blog.csdn.net/qwertyupoiuytr/article/details/65667552


猜你喜欢
- mysql取json字符串字段下的某个键的值要求:mysql版本5.7及以上SELECT JSON_EXTRACT('{"
- python之循环遍历关于循环遍历大家都知道,不外乎for和while,今天我在这写点不一样的循环和遍历。在实践中有时会遇到删除列表中的元素
- 逻辑判断与逻辑语句对于─件事情正确与否(真假的判断) √ X根据判断的结果做不同的事情,就是我们的逻辑业务对于条件满足的判断语句,就是条件语
- 本文实例讲述了Python模块的定义,模块的导入,__name__用法。分享给大家供大家参考,具体如下:相关内容:什么是模块模块的导入同级目
- 装饰器通用模型def wrapper(fn): def inner(*args, **kwargs):  
- QPixmap 像素图控件是用来处理图像的控件之一。它用于将优化后的图像显示在屏幕上。在我们的代码示例中,我们将使用QPixmap 控件在程
- 目录一、变量、常量的区别二、变量1. Python中的变量不需要声明类型2. 用“=”号来给变量赋值3. 赋值4. 变量5. “=”6. P
- 环境介绍python3.5.2 64位django 1.10.3apache 2.4 64位windows 10重点在apache上。pyt
- finetune分为全局finetune和局部finetune。首先介绍一下局部finetune步骤:1.固定参数 for na
- 一、跨域是什么从一个域名去请求另一个域名,这个过程称之为跨域。浏览器从一个域名的网页去请求另一个域名的资源,域名、端口、协议有一个不一样,请
- 机器视觉从Google的无人驾驶汽车到可以识别假钞的自动售卖机,机器视觉一直都是一个应用广泛且具有深远的影响和雄伟的愿景的领域。这里我们将重
- 对于编译型的语言,比如C#中的一个.cs文件,Java中的一个.java或者编译后的.class文件可以认为是一个模块(但常常不表述为模块)
- js表单验证只能是写限定的东西大收集 代码如下:ENTER键可以让光标移到下一个输入框<input onkeydown=&q
- python+selenium编写实现爬虫过程:1.爬虫循环处理table表,2.table表分页处理,3.网页table所有内容循环处理4
- sort()方法排序列表中的对象,比较使用func(如果给定)。语法以下是sort()方法的语法:list.sort([func
- 首先检查MySQL 服务没有启动》如果没有启动,则要启动这个服务。有时候安装mysql后使用mysql命令时报错 Can'
- PDOStatement::errorInfoPDOStatement::errorInfo — 获取跟上一次语句句柄操作相关的扩展错误信息
- 最近心情非常差,而且还没有触底的样子,哎~~~总是会忍不住叹气~~~前些日子在Twitter上叨唠说“不在乎IE8什么时候推出,只在乎IE6
- 一、什么是pywinautoPywinauto是基于Python开发的,用于操作Windows标准图形界面的自动化测试的脚本模块。二、pyw
- 1、简介 with是从Python2.5引入的一个新的语法,它是一种上下文管理协议,目的