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

yipeiwu_com5年前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()

运行结果示例:

服务器端:

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

客户端(服务器端做了端口映射:59999->9999):

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

以上这篇python单线程文件传输的实例(C/S)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Django集成搜索引擎Elasticserach的方法示例

1.背景 当用户在搜索框输入关键字后,我们要为用户提供相关的搜索结果。可以选择使用模糊查询 like 关键字实现,但是 like 关键字的效率极低。查询需要在多个字段中进行,使用 li...

python微信跳一跳系列之棋子定位像素遍历

python微信跳一跳系列之棋子定位像素遍历

前言 在前几篇博客中,分别就棋子的颜色识别、模板匹配等定位方式进行了介绍和实践,这一篇博客就来验证一下github中最热门的跳一跳外挂中采用的像素遍历的方法。 方法说明 像素遍历的实质依...

Python中的两个内置模块介绍

使用了Python一段时间后,可以说Python的基本单位就是模块了,在使用模块的时候我们一般会使用通过import语句来将其导入,但是我们在没有导入任何模块的时候,我们却能使用这样的一...

python基础教程之循环介绍

循环用于重复执行一些程序块。从上一讲的选择结构,我们已经看到了如何用缩进来表示程序块的隶属关系。循环也会用到类似的写法。 for循环 for循环需要预先设定好循环的次数(n),然后执行隶...

浅谈Django自定义模板标签template_tags的用处

浅谈Django自定义模板标签template_tags的用处

自定义模板标签,过滤器。英文翻译是Customtemplatetagsandfilters。customfilter自定义过滤器今天不在我的记录范围之内,以后用到再看官方文档也不迟。 *...