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)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Python Socket传输文件示例

    发送端可以不停的发送新文件,接收端可以不停的接收新文件. 例如:发送端输入:e:\visio.rar,接收端会默认保存为 e:\new_visio.rar,支持多并发,具体实现如下: 接收端: 方法一: #-*- coding: UTF-8 -*- import socket,time,SocketServer,struct,os,thread host='192.168.50.74' port=12307 s=socket.socket(socket.AF_INET,socket.SOCK_S

  • python cs架构实现简单文件传输

    本文为大家分享了python cs架构实现简单文件的传输代码,供大家参考,具体内容如下 要实现简单文件的传输我们必须考虑这些问题: 1.什么是c/s架构? 顾名思义,就是客户端端/服务器架构.不同的人可能回答不一,但是有一点是相同的:服务器是一个软件或硬件,用于向一个或多个客户端提供所需要的服务,服务器存在的唯一目的就是等待客户的请求,给这些客户服务,然后等待其他的请求. 2.客户端与服务端如何通信? 其实说白了就是互联网中两个主机该如何通信,首先我们用ip地址可以标示一台主机,这样就可以通信了

  • python多进程实现文件下载传输功能

    本文实例为大家分享了python多进程实现文件下载传输功能的具体代码,供大家参考,具体内容如下 需求: 实现文件夹拷贝功能(包括文件内的文件),并打印拷贝进度 模块: os模块 multiprocessing 模块 代码: import multiprocessing import os def deal_file(old_dir,new_dir,file_name,queue): # 打开以存在文件 old_file = open(os.path.join(old_dir,file_name)

  • Python实现的简单文件传输服务器和客户端

    还是那个题目(题目和流程见java版本),感觉光用java写一点新意也没有,恰巧刚学习了python,何不拿来一用,呵呵: 服务器端: import SocketServer, time class MyServer(SocketServer.BaseRequestHandler): userInfo = { 'yangsq' : 'yangsq', 'hudeyong' : 'hudeyong', 'mudan' : 'mudan' } def handle(self): print 'Con

  • Python实现基于C/S架构的聊天室功能详解

    本文实例讲述了Python实现基于C/S架构的聊天室功能.分享给大家供大家参考,具体如下: 一.课程介绍 1.简介 本次项目课是实现简单聊天室程序的服务器端和客户端. 2.知识点 服务器端涉及到asyncore.asynchat和socket这几个模块,客户端用到了telnetlib.wx.time和thread这几个模块. 3.所需环境 本次课中编写客户端需要用到wxPython,它是一个GUI工具包,请先使用下面的命令安装: $ sudo apt-get install python-wxt

  • 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.flo

  • java 实现局域网文件传输的实例

    java 实现局域网文件传输的实例 本文主要实现局域网文件传输的实例,对java 的TCP知识,文件读写,Socket等知识的理解应用,很好的实例,大家参考下, 实现代码: ClientFile.java /** * 更多资料欢迎浏览凯哥学堂官网:http://kaige123.com * @author 小沫 */ package com.tcp.file; import java.io.File; import java.io.FileInputStream; import java.io.

  • python shutil文件操作工具使用实例分析

    这篇文章主要介绍了python shutil文件操作工具使用实例分析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 python中的shutil是一种高层次的文件操作工具,主要强大之处在于对文件的复制与删除操作更友好 一:shutil. copyfileobj(fsrc,fdst [23]) 将 fsrc 的内容复制到 fdst.如果给出整数长度,则为缓冲区大小.注意,fsrc.fdst,必须是已经打开的文件,而不能传入文件名的字符串 def

  • Delphi实现木马文件传输代码实例

    本文以实例形式讲述了Delphi下木马的文件传输方法的实现过程,具体步骤如下: 服务器端代码: unit ServerFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, ExtCtrls,WinSock; type TfrmMain = class(TForm) Panel1: TPanel; Labe

  • python复制文件的方法实例详解

    本文实例讲述了python复制文件的方法.分享给大家供大家参考.具体分析如下: 这里涉及Python复制文件在实际操作方案中的实际应用以及Python复制文件 的相关代码说明,希望你会有所收获. Python复制文件: import shutil import os import os.path src = " d:\\download\\test\\myfile1.txt " dst = " d:\\download\\test\\myfile2.txt " ds

  • Python实现FTP文件传输的实例

    FTP一般流程 FTP对应PASV和PORT两种访问方式,分别为被动和主动,是针对FTP服务器端进行区分的,正常传输过程中21号端口用于指令传输,数据传输端口使用其他端口. PASV:由客户端发起数据传输请求,服务器端返回并携带数据端口,并且服务器端开始监听此端口等待数据,为被动模式: PORT:客户端监听端口并向服务器端发起请求,服务器端主动连接此端口进行数据传输,为主动模式. 其中TYPE分两种模式,I对应二进制模式.A对应ASCII模式: PASV为客户端发送请求,之后227为服务器端返回

  • Python接口测试文件上传实例解析

    接口测试中,上传文件的测试场景非常常见.例如:上传头像(图片).上传文件.上传视频等.下面以一个上传图片的例子为大家讲解如何通过 python 测试上传文件接口. 首先通过抓包分析上传文件接口的请求参数: 下面是上传文件接口脚本.把目标文件以open打开,然后存储到变量file.并且使用files参数指明请求的参数名称.上传文件的类型.以及上传文件的路径. 这里注意:content-type参数,如果我们通过form-data的方式上传文件,我们发送post请求的时候,headers这个参数中一

  • python 合并文件的具体实例

    支持两种用法:(1)合并某一文件夹下的所有文件(忽略文件夹等非文件条目)(2)显示的合并多文件. 复制代码 代码如下: import sysimport os'''    usage(1): merge_files pathname              pathname is directory and merge files in pathname directory    usage(2): merge_files file1 file2 [file3[...]]'''FILE_SLI

  • Python实现文件信息进行合并实例代码

    将电话簿TeleAddressBook.txt和电子邮件EmailAddressBook.txt合并为一个完整的AddressBook.txt def main(): ftele1=open("d:\TeleAddressBook.txt","rb") ftele2=open("d:\EmailAddressBook.txt","rb") ftele1.readline() ftele2.readline() lines1=f

  • python实现FTP文件传输的方法(服务器端和客户端)

    用python实现FTP文件传输,包括服务器端和客户端,要求 (1)客户端访问服务器端要有一个验证功能 (2)可以有多个客户端访问服务器端 (3)可以对重名文件重新上传或下载 FTP(File Transfer Protocol,文件传输协议) 是 TCP/IP 协议组中的协议之一.FTP协议包括两个组成部分,其一为FTP服务器,其二为FTP客户端.其中FTP服务器用来存储文件,用户可以使用FTP客户端通过FTP协议访问位于FTP服务器上的资源.在开发网站的时候,通常利用FTP协议把网页或程序传

随机推荐