您好,登錄后才能下訂單哦!
python中怎么實(shí)現(xiàn)單線程文件傳輸,相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。
客戶端代碼:
#-*-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()
服務(wù)器端代碼:
#-*-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()
運(yùn)行結(jié)果示例:
服務(wù)器端:
客戶端(服務(wù)器端做了端口映射:59999->9999):
看完上述內(nèi)容,你們掌握python中怎么實(shí)現(xiàn)單線程文件傳輸?shù)姆椒藛??如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。