用python socket模塊實現簡單的文件下載
阿新 • • 發佈:2019-01-19
mage 文件下載 accep p s line 註釋 os.path 捕獲 bubuko
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("客戶端已經斷開") break cmd, filename = data.decode().split() # ex: get name.txt if os.path.isfile(filename): f = open(filename, "rb") # 獲取文件的字節大小 size = os.stat(filename).st_size conn.send(str(size).encode()) # 發送文件大小 conn.recv(1024) for line in f: # 客戶端確認後發送文件內容 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()) # 發送請求 server_response = client.recv(1024) if server_response.decode().startswith("not"): print("請輸入有效文件名") continue client.send(b"ready to recv file") # 發送確認 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: # 最後一次了,剩多少收多少,防止之後發送數據粘包 size = file_size - rece_size print("last receive:", size) recv_data = client.recv(size) rece_size += len(recv_data) # 累加接受數據大小 f.write(recv_data) # 寫入文件,即下載 else: print("文件下載完成") f.close() client.close()
測試案例:
主要是socket的簡單使用,主要節點都有註釋
用python socket模塊實現簡單的文件下載