如何使用python socket模塊實現(xiàn)簡單的文件下載
更新時間:2020年09月04日 10:20:11 作者:侯賽雷
這篇文章主要介紹了如何使用python socket模塊實現(xiàn)簡單的文件下載,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下
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: # 客戶端確認后發(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ā)送確認
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)簡單的文件下載的詳細內(nèi)容,更多關(guān)于python socket文件下載的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
PyCharm2020.1.2社區(qū)版安裝,配置及使用教程詳解(Windows)
這篇文章主要介紹了PyCharm2020.1.2社區(qū)版安裝,配置及使用教程(Windows),本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08
numpy創(chuàng)建神經(jīng)網(wǎng)絡(luò)框架
本文介紹了使用numpy從零搭建了一個類似于pytorch的深度學(xué)習(xí)框架,可以用在很多地方,有需要的朋友可以自行參考一下2021-08-08
python 3調(diào)用百度OCR API實現(xiàn)剪貼板文字識別
這篇文章主要為大家詳細介紹了python 3調(diào)用百度OCR API實現(xiàn)剪貼板文字識別,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-09-09

