python多線程檔案傳輸範例(C/S)__python

來源:互聯網
上載者:User

用戶端代碼:

#-*-encoding:utf-8-*-

 

import socket

import os

import sys

import math

import time

import threading

 

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 thread count

        client.send(str(threadCount))

        response = client.recv(1024)

        # send file content

        for i in range(threadCount):

            filePartSender = threading.Thread(target=transferFileSubThread, args=(fileFullPath, i+1, fileSize))

            filePartSender.start()

        

        for i in range(threadCount):

            sem.acquire()

        timeEnd = time.clock()

        print "Finished, spent %f seconds" % (timeEnd - timeStart)

    else:

        print "File doesn't exist"

 

def transferFileSubThread(fileFullPath, threadIndex, fileSize):

    try:

        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        client.connect((targetHost, targetPort))

        client.send(str(threadIndex))

        client.recv(1024)

        # calculate start position and end position

        filePartSize = fileSize / threadCount

        startPosition = filePartSize * (threadIndex - 1)

        #print "Thread : %d, startPosition: %d" % (threadIndex, startPosition)

        endPosition = filePartSize * threadIndex - 1

        if threadIndex == threadCount:

            endPosition = fileSize - 1

            filePartSize = fileSize - startPosition

        file = open(fileFullPath, "rb")

        file.seek(startPosition)

        sentLength = 0

        while sentLength < filePartSize:

            bufLen = 1024

            lengthLeft = filePartSize - sentLength

            if lengthLeft < 1024:

                bufLen = lengthLeft

            buf = file.read(bufLen)

            client.send(buf)

            sentLength += len(buf)

        file.close()

        sem.release()

        print "Part %d finished, size sent %d" % (threadIndex, sentLength)

    except Exception, e:

        print e

 

targetHost = raw_input("Server IP Address: ")

targetPort = int(raw_input("Server port: "))

threadCount = int(raw_input("Thread count: "))

sem = threading.Semaphore(0)

 

while True:

    transferFile()

 

伺服器端代碼:

#-*-encoding:utf-8-*-

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.