tcp进行文件传输看这里–python 实现TCP文件接发
这里实现的接收方一直接收,发送方每次发送一个文件,方便我在其他函数中调用发送文件。
使用udp 容易出现丢包现象需要处理
要注意 tcp 和udp的套接字不一样
udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
tcp_socketr = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
1、发送
import threading
import socket
import tqdm
import os
import cv2
from time import ctime, sleep
def send(address, filename):
SEPARATOR = '<SEPARATOR>'
host, port = address
Buffersize = 4096*10
filename = filename
file_size = os.path.getsize(filename)
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
print(f'服务器连接中{host}:{port}')
s.connect((host, port))
print('与服务器连接成功')
s.send(f'{filename}{SEPARATOR}{file_size}'.encode('utf-8'))
progress = tqdm.tqdm(range(file_size), 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:
print('exit退出传输,传输完毕!')
s.sendall('file_download_exit'.encode('utf-8'))
break
s.sendall(bytes_read)
progress.update(len(bytes_read))
sleep(0.001)
s.close()
if __name__ == '__main__':
address = ('127.0.0.1', 1234)
filename = input('请输入文件名:')
t = threading.Thread(target=send, args=(address, filename))
t.start()
2、接收
import socket
import tqdm
import os
import threading
def recvived(address, port):
SEPARATOR = '<SEPARATOR>'
Buffersize = 4096*10
while True:
print('准备接收新的文件...')
udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
udp_socket.bind((address, port))
recv_data = udp_socket.recvfrom(Buffersize)
recv_file_info = recv_data[0].decode('utf-8')
print(f'接收到的文件信息{recv_file_info}')
c_address = recv_data[1]
print(f'客户端{c_address}连接')
filename ,file_size = recv_file_info.split(SEPARATOR)
filename = os.path.basename(filename)
file_size = int(file_size)
progress = tqdm.tqdm(range(file_size), f'接收{filename}', unit='B', unit_divisor=1024, unit_scale=True)
with open('8_18_'+filename,'wb') as f:
for _ in progress:
bytes_read = udp_socket.recv(Buffersize)
if bytes_read == b'file_download_exit':
print('完成传输!')
print(bytes_read)
break
f.write(bytes_read)
progress.update(len(bytes_read))
udp_socket.close()
if __name__ == '__main__':
port = 1234
address = "127.0.0.1"
t = threading.Thread(target=recvived, args=(address, port))
t.start()
|