python单线程文件传输的实例(C/S)

作者:远行的风 时间:2023-04-07 22:45:48 

客户端代码:


#-*-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)

来源:https://blog.csdn.net/qwertyupoiuytr/article/details/65667552

标签:python,单线程,文件,传输
0
投稿

猜你喜欢

  • PHP实现获取第一个中文首字母并进行排序的方法

    2023-10-30 12:29:08
  • 用MyEclipse配置DataBase Explorer(图示)

    2024-01-26 01:43:28
  • python中元类用法实例

    2023-10-24 19:12:29
  • GO语言常用的文件读取方式

    2024-05-21 10:21:30
  • 用 JavaScript 解数学题

    2010-07-09 13:38:00
  • js键盘事件全面控制

    2008-02-21 12:51:00
  • PHP的mysqli_thread_id()函数讲解

    2023-06-13 10:09:43
  • js删除所有的cookie的代码

    2024-05-02 17:29:59
  • VS Code有哪些奇技淫巧(必知)

    2022-01-07 21:10:47
  • openCV中值滤波和均值滤波的代码实现

    2023-07-22 06:08:28
  • sqlserver中触发器+游标操作实现

    2024-01-20 19:25:42
  • python一行输入多值的实现详解

    2021-07-02 06:52:39
  • 细数JavaScript 一个等号,两个等号,三个等号的区别

    2023-08-25 08:22:09
  • 浅谈numpy.where() 的用法和np.argsort()的用法说明

    2022-03-12 01:52:23
  • access MDB 转换为 Execl(ASP类)

    2008-07-19 12:10:00
  • ASP制作中使用MYSQL的分析

    2008-10-13 09:25:00
  • 用ASP生成XBM数字图片验证码

    2008-08-10 18:40:00
  • Tensorflow 定义变量,函数,数值计算等名字的更新方式

    2021-08-10 22:48:09
  • python中的list字符串元素排序

    2022-03-14 12:27:14
  • linux下mysql开启远程访问权限 防火墙开放3306端口

    2024-01-24 10:59:14
  • asp之家 网络编程 m.aspxhome.com