python單線程文件傳輸?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()
運行結(jié)果示例:
服務(wù)器端:

客戶端(服務(wù)器端做了端口映射:59999->9999):

以上這篇python單線程文件傳輸?shù)膶嵗?C/S)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python使用wxPython和PyMuPDF實現(xiàn)合并PDF文檔
處理大量的PDF文檔可能會變得復(fù)雜和耗時,但是,使用Python編程和一些強大的庫,可以使這個任務(wù)變得簡單而高效,下面我們就來看看Python如何使用wxPython和PyMuPDF合并PDF文檔并自動復(fù)制到剪貼板吧2023-11-11
Python+matplotlib實現(xiàn)餅圖的繪制
Matplotlib是一個Python的2D繪圖庫,它以各種硬拷貝格式和跨平臺的交互式環(huán)境生成出版質(zhì)量級別的圖形。本文將利用Matplotlib庫繪制餅圖,感興趣的可以了解一下2022-03-03
Python實現(xiàn)將MySQL數(shù)據(jù)庫表中的數(shù)據(jù)導(dǎo)出生成csv格式文件的方法
這篇文章主要介紹了Python實現(xiàn)將MySQL數(shù)據(jù)庫表中的數(shù)據(jù)導(dǎo)出生成csv格式文件的方法,涉及Python針對mysql數(shù)據(jù)庫的連接、查詢、csv格式數(shù)據(jù)文件的生成等相關(guān)操作技巧,需要的朋友可以參考下2018-01-01
Pytorch使用PIL和Numpy將單張圖片轉(zhuǎn)為Pytorch張量方式
這篇文章主要介紹了Pytorch使用PIL和Numpy將單張圖片轉(zhuǎn)為Pytorch張量方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05
在Python中執(zhí)行系統(tǒng)命令的方法示例詳解
最近在做那個測試框架的時候發(fā)現(xiàn)對python執(zhí)行系統(tǒng)命令不太熟悉,所以想著總結(jié)下,下面這篇文章主要給大家介紹了關(guān)于在Python中執(zhí)行系統(tǒng)命令的方法,需要的朋友可以參考借鑒,下面來一起看看吧。2017-09-09
Python移動測試開發(fā)subprocess模塊項目實戰(zhàn)
這篇文章主要為大家介紹了Python移動測試開發(fā)subprocess模塊項目實戰(zhàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07
使用Selenium控制當前已經(jīng)打開的chrome瀏覽器窗口
有時通過selenium打開網(wǎng)站時,發(fā)現(xiàn)有些網(wǎng)站需要掃碼登錄,就很頭疼,導(dǎo)致爬蟲進展不下去,下面這篇文章主要給大家介紹了關(guān)于使用Selenium控制當前已經(jīng)打開的chrome瀏覽器窗口的相關(guān)資料,需要的朋友可以參考下2022-07-07
Python迭代器iterator生成器generator使用解析
這篇文章主要介紹了Python迭代器iterator生成器generator使用解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-10-10

