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
0
投稿
猜你喜欢
- 前言前面在 BeanShell 里面是通过 java 脚本实现请求的预处理,jmeter里面也可以调用python的脚本,需安装 jytho
- socket解析HTTP请求内容思路1. 解析HTTP请求的头部HTTP请求头部的结束符行为"\r\n",可以按行读取H
- 前言大家都知道Python 是一门强类型、动态类型检查的语言。所谓动态类型,是指在定义变量时,我们无需指定变量的类型,Python 解释器会
- 一、使用 print() 函数在 Python 中,print() 函数支持格式化输出,与 C 语言的 printf 类似。1. 格式化输出
- 本文实例讲述了JavaScript导出Excel的方法。分享给大家供大家参考。具体实现方法如下:<html xmlns="h
- AdobeAdobe公司的标识1982年,40多岁的程序员约翰·沃诺克(John Warnock)和查尔斯·杰斯克(Charles Gesc
- 类:定义一件事物的抽象特点。对象:类的 实例。成员变量 − 定义在类内部的变量。该变量的值对外是不可见的,但是可以通过成
- 要开发一个基于数据库的应用系统,其中最关键的一步就是整个系统所依据的数据库的建模设计,从逻辑的到物理的,一个环节疏于设计,整个的应用系统便似
- 综述:本文讨论了VBScript和 JScript之间的区别,以及它们的使用场合。推荐:Vbscript5.5中文语言参考手册chm格式下载
- 用ASP生成XBM数字图片(可用来生成验证码)XBM图片是一个纯文本的文件,可以用ASP来自动生成。可以用它来使用网站登陆的验证码;我们用记
- 所谓类属性的延迟计算就是将类的属性定义成一个property,只在访问的时候才会计算,而且一旦被访问后,结果将会被缓存起来,不用每次都计算。
- 加密解密字符串的asp函数,如用于ASP链接地址栏参数的加密,看代码就明白。比如:show.asp?id=DB26538FA54C70E1E
- 一、前言关于什么是Dapper(详细入口),在此不做赘述;本文仅对Dapper在.Net Core中的使用作扼要说明,所陈代码以示例讲解为主
- 循环和列表不管怎样,程序会做一些重复的事情,下面我们就用for循环打印一个列表变量。做这个练习的时候你必须自己弄懂它们的含义和作用。在使用f
- 大家在打开带有图片的网页时,有时会看到这样的情况:当鼠标指向图片的不同部位时,可以打开不同的超链接,这
- 一 前期说明:我运行项目的环境是nginx+php,存储代码用的是gitlab,python版本:3.6 django版本:2.2.1 my
- 在这篇文章中,我将展示如何在 CentOS/RHEL 7、Debian 以及它的衍生版本比如 Ubuntu(最新的 Ubuntu 16.04
- 数据库系统的安全性包括很多方面。由于很多情况下,数据库服务器容许客户机从网络上连接,因此客户机连接的安全对MySQL数据库安全有很重要的影响
- 格式化字符串是什么?Python字符串的格式化处理主要是用来将变量(对象)的值填充到字符串中,在字符串中解析Python表达式,对字符串进行
- PHP asXML()函数实例格式化 XML(版本 1.0)中的 SimpleXML 对象的数据:<?php $note=<&l