如何使用python socket模塊實現(xiàn)簡單的文件下載
server端:
# ftp server端 import socket, os, time server = socket.socket() server.bind(("localhost", 8080)) server.listen() while True: conn, addr = server.accept() print("連接到客戶端:", addr) while True: try: # windows會直接報錯,需要捕獲異常 data = conn.recv(1024) if not data: print("客戶端已斷開") break except Exception as e: print("客戶端已經(jīng)斷開") break cmd, filename = data.decode().split() # ex: get name.txt if os.path.isfile(filename): f = open(filename, "rb") # 獲取文件的字節(jié)大小 size = os.stat(filename).st_size conn.send(str(size).encode()) # 發(fā)送文件大小 conn.recv(1024) for line in f: # 客戶端確認(rèn)后發(fā)送文件內(nèi)容 conn.send(line) f.close() print("文件下載完成") conn.send("not file".encode()) server.close()
client端:
import socket client = socket.socket() client.connect(("localhost", 8080)) while True: cmd = input(">>:").strip() if len(cmd)==0: continue if cmd.startswith("get"): client.send(cmd.encode()) # 發(fā)送請求 server_response = client.recv(1024) if server_response.decode().startswith("not"): print("請輸入有效文件名") continue client.send(b"ready to recv file") # 發(fā)送確認(rèn) file_size = int(server_response.decode()) # 獲取文件大小 rece_size=0 filename = cmd.split()[1] f = open(filename + ".new", "wb") while rece_size < file_size: if file_size - rece_size > 1024: # 要收不止一次 size = 1024 else: # 最后一次了,剩多少收多少,防止之后發(fā)送數(shù)據(jù)粘包 size = file_size - rece_size print("last receive:", size) recv_data = client.recv(size) rece_size += len(recv_data) # 累加接受數(shù)據(jù)大小 f.write(recv_data) # 寫入文件,即下載 else: print("文件下載完成") f.close() client.close()
測試案例:
以上就是如何使用python socket模塊實現(xiàn)簡單的文件下載的詳細(xì)內(nèi)容,更多關(guān)于python socket文件下載的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python讀取sqlite數(shù)據(jù)庫文件的方法分析
這篇文章主要介紹了Python讀取sqlite數(shù)據(jù)庫文件的方法,結(jié)合實例形式分析了Python引入sqlite3模塊操作sqlite數(shù)據(jù)庫的讀取、SQL命令執(zhí)行等相關(guān)操作技巧,需要的朋友可以參考下2017-08-08Django中ORM表的創(chuàng)建和增刪改查方法示例
這篇文章主要給大家介紹了關(guān)于Django中ORM表的創(chuàng)建和增刪改查等基本操作的方法,還給大家分享了django orm常用查詢篩選的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-11-11Python的selenium模塊使用find_element_by_id無效解決方案
這篇文章主要介紹了Python的selenium模塊使用find_element_by_id無效解決方案,find_element_by_id無效可能是因為版本問題,而4.5.0版本不支持頁面對象的定位find_element_by_id方法,以前版本支持這些進(jìn)行元素定位,需要的朋友可以參考下2023-12-12Python 基于Twisted框架的文件夾網(wǎng)絡(luò)傳輸源碼
這篇文章主要介紹了Python 基于Twisted框架的文件夾網(wǎng)絡(luò)傳輸源碼,需要的朋友可以參考下2016-08-08python神經(jīng)網(wǎng)絡(luò)Keras實現(xiàn)LSTM及其參數(shù)量詳解
這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡(luò)Keras實現(xiàn)LSTM及其參數(shù)量詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05Python pandas 重命名索引和列名稱的實現(xiàn)
本文主要介紹了Python pandas 重命名索引和列名稱的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07