python單線程文件傳輸?shù)膶?shí)例(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()
服務(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):

以上這篇python單線程文件傳輸?shù)膶?shí)例(C/S)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- python Socket網(wǎng)絡(luò)編程實(shí)現(xiàn)C/S模式和P2P
- python基于C/S模式實(shí)現(xiàn)聊天室功能
- Python實(shí)現(xiàn)基于C/S架構(gòu)的聊天室功能詳解
- Python socket套接字實(shí)現(xiàn)C/S模式遠(yuǎn)程命令執(zhí)行功能案例
- Python socket C/S結(jié)構(gòu)的聊天室應(yīng)用實(shí)現(xiàn)
- python3編寫(xiě)C/S網(wǎng)絡(luò)程序?qū)嵗坛?/a>
- 基于python實(shí)現(xiàn)簡(jiǎn)單C/S模式代碼實(shí)例
相關(guān)文章
python實(shí)現(xiàn)簡(jiǎn)單登陸流程的方法
下面小編就為大家分享一篇python實(shí)現(xiàn)簡(jiǎn)單登陸流程的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04
Python實(shí)現(xiàn)matplotlib顯示中文的方法詳解
這篇文章主要介紹了Python實(shí)現(xiàn)matplotlib顯示中文的方法,結(jié)合實(shí)例形式詳細(xì)總結(jié)分析了Python使用matplotlib庫(kù)繪圖時(shí)顯示中文的相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下2018-02-02
pygame實(shí)現(xiàn)一個(gè)類(lèi)似滿天星游戲流程詳解
這篇文章主要介紹了使用pygame來(lái)編寫(xiě)類(lèi)滿天星游戲的全記錄,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2022-09-09
如何解決vscode下powershell終端進(jìn)入python虛擬環(huán)境venv問(wèn)題
這篇文章主要介紹了如何解決vscode下powershell終端進(jìn)入python虛擬環(huán)境venv問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
tensorflow 動(dòng)態(tài)獲取 BatchSzie 的大小實(shí)例
這篇文章主要介紹了tensorflow 動(dòng)態(tài)獲取 BatchSzie 的大小實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06
Numpy中stack(),hstack(),vstack()函數(shù)用法介紹及實(shí)例
這篇文章主要介紹了Numpy中stack(),hstack(),vstack()函數(shù)用法介紹及實(shí)例,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01
Python實(shí)現(xiàn)讀取機(jī)器硬件信息的方法示例
這篇文章主要介紹了Python實(shí)現(xiàn)讀取機(jī)器硬件信息的方法,涉及Python針對(duì)計(jì)算機(jī)注冊(cè)表、操作系統(tǒng)、處理器、網(wǎng)絡(luò)等常見(jiàn)硬件信息讀取操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-06-06
修改python plot折線圖的坐標(biāo)軸刻度方法
今天小編就為大家分享一篇修改python plot折線圖的坐標(biāo)軸刻度方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-12-12

