如何使用python socket模塊實(shí)現(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會直接報(bào)錯(cuò),需要捕獲異常 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_sizeprint('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模塊實(shí)現(xiàn)簡單的文件下載的詳細(xì)內(nèi)容,更多關(guān)于python socket文件下載的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)2. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁的方法3. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究4. XHTML 1.0:標(biāo)記新的開端5. ASP基礎(chǔ)知識VBScript基本元素講解6. 利用CSS3新特性創(chuàng)建透明邊框三角7. XML入門的常見問題(四)8. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實(shí)現(xiàn)代碼9. 詳解CSS偽元素的妙用單標(biāo)簽之美10. HTML5 Canvas繪制圖形從入門到精通
