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ù)自己需求修改,簡單局域網(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('請輸入文件名:')
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()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python?pyaudio音頻錄制的實(shí)現(xiàn)
這篇文章主要介紹了python?pyaudio音頻錄制的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05
Python配置文件解析模塊ConfigParser使用實(shí)例
這篇文章主要介紹了Python配置文件解析模塊ConfigParser使用實(shí)例,本文講解了figParser簡介、ConfigParser 初始工作、ConfigParser 常用方法、ConfigParser使用實(shí)例等內(nèi)容,需要的朋友可以參考下2015-04-04
python 列表推導(dǎo)和生成器表達(dá)式的使用
這篇文章主要介紹了python 列表推導(dǎo)和生成器表達(dá)式的使用方法,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2021-02-02
Mac上Python使用ffmpeg完美解決方案(避坑必看!)
ffmpeg是一個(gè)強(qiáng)大的開源命令行多媒體處理工具,下面這篇文章主要給大家介紹了關(guān)于Mac上Python使用ffmpeg完美解決方案的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02

