python實(shí)現(xiàn)TCP文件接收發(fā)送
本文實(shí)例為大家分享了python實(shí)現(xiàn)TCP文件接收發(fā)送的具體代碼,供大家參考,具體內(nèi)容如下
下一篇分享:udp收發(fā)的實(shí)現(xiàn)
先運(yùn)行服務(wù)器端打開接收,在運(yùn)行客服端發(fā)送文件
還有記得改一下ip喲
1、發(fā)送
根據(jù)自己需求修改,簡(jiǎn)單局域網(wǎng)下完成文件收發(fā)
客戶端
# 由客戶端向服務(wù)器傳數(shù)據(jù),文件 import socket import tqdm import os def send(filename): # 傳輸數(shù)據(jù)間隔符 SEPARATOR = '<SEPARATOR>' # 服務(wù)器信息 host = '127.0.0.1' port =1234 # 文件緩沖區(qū) Buffersize = 4096*10 # 傳輸文件名字 filename = filename # 文件大小 file_size = os.path.getsize(filename) # 創(chuàng)建socket鏈接 s = socket.socket() print(f'服務(wù)器連接中{host}:{port}') s.connect((host, port)) print('與服務(wù)器連接成功') # 發(fā)送文件名字和文件大小,必須進(jìn)行編碼處理 s.send(f'{filename}{SEPARATOR}{file_size}'.encode()) # 文件傳輸 progress = tqdm.tqdm(range(file_size), f'發(fā)送{filename}', unit='B', unit_divisor=1024) with open(filename,'rb') as f : # 讀取文件 for _ in progress: bytes_read = f.read(Buffersize) if not bytes_read: break # sendall 確保網(wǎng)絡(luò)忙碌的時(shí)候,數(shù)據(jù)仍然可以傳輸 s.sendall(bytes_read) progress.update(len(bytes_read)) # 關(guān)閉資源 s.close() if __name__ == '__main__': filename = input('請(qǐng)輸入文件名:') send(filename)
2、接收
服務(wù)器端
import socket import tqdm import os import threading def received(): # 設(shè)置服務(wù)器的ip和 port # 服務(wù)器信息 sever_host = '127.0.0.1' sever_port =1234 # 傳輸數(shù)據(jù)間隔符 SEPARATOR = '<SEPARATOR>' # 文件緩沖區(qū) Buffersize = 4096*10 s = socket.socket() s.bind((sever_host, sever_port)) # 設(shè)置監(jiān)聽數(shù) s.listen(128) print(f'服務(wù)器監(jiān)聽{sever_host}:{sever_port}') # 接收客戶端連接 client_socket, address = s.accept() # 打印客戶端ip print(f'客戶端{(lán)address}連接') # 接收客戶端信息 received = client_socket.recv(Buffersize).decode() filename ,file_size = received.split(SEPARATOR) # 獲取文件的名字,大小 filename = os.path.basename(filename) file_size = int(file_size) # 文件接收處理 progress = tqdm.tqdm(range(file_size), f'接收{(diào)filename}', unit='B', unit_divisor=1024, unit_scale=True) with open('8_18_'+filename,'wb') as f: for _ in progress: # 從客戶端讀取數(shù)據(jù) bytes_read = client_socket.recv(Buffersize) # 如果沒有數(shù)據(jù)傳輸內(nèi)容 if not bytes_read: break # 讀取寫入 f.write(bytes_read) # 更新進(jìn)度條 progress.update(len(bytes_read)) # 關(guān)閉資源 client_socket.close() s.close() if __name__ == '__main__': received()
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持本站。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。