python单线程文件传输的实例(C/S)
更新时间:2019年02月13日 10:09:21 作者:远行的风
今天小编就为大家分享一篇python单线程文件传输的实例(C/S),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
客户端代码:
#-*-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):

以上这篇python单线程文件传输的实例(C/S)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Python使用wxPython和PyMuPDF实现合并PDF文档
处理大量的PDF文档可能会变得复杂和耗时,但是,使用Python编程和一些强大的库,可以使这个任务变得简单而高效,下面我们就来看看Python如何使用wxPython和PyMuPDF合并PDF文档并自动复制到剪贴板吧2023-11-11
Python实现将MySQL数据库表中的数据导出生成csv格式文件的方法
这篇文章主要介绍了Python实现将MySQL数据库表中的数据导出生成csv格式文件的方法,涉及Python针对mysql数据库的连接、查询、csv格式数据文件的生成等相关操作技巧,需要的朋友可以参考下2018-01-01
Pytorch使用PIL和Numpy将单张图片转为Pytorch张量方式
这篇文章主要介绍了Pytorch使用PIL和Numpy将单张图片转为Pytorch张量方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-05-05
使用Selenium控制当前已经打开的chrome浏览器窗口
有时通过selenium打开网站时,发现有些网站需要扫码登录,就很头疼,导致爬虫进展不下去,下面这篇文章主要给大家介绍了关于使用Selenium控制当前已经打开的chrome浏览器窗口的相关资料,需要的朋友可以参考下2022-07-07
Python迭代器iterator生成器generator使用解析
这篇文章主要介绍了Python迭代器iterator生成器generator使用解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2019-10-10


最新评论