使用python,通过网络传输一个文件,对比tcp和dup传输特点。对于大文件,需要屏幕打印传输剩余时间,已经传输的百分比信息
时间: 2024-03-09 16:22:33 浏览: 29
TCP传输特点:
- 可靠性更高,能够保证数据的完整性和有序性。
- 传输速度较慢,因为需要等待确认和重传丢失的数据包。
- 消耗的系统资源较多。
UDP传输特点:
- 传输速度较快,因为没有确认和重传丢失的数据包的过程。
- 可靠性较低,数据包的丢失和乱序是常见的情况。
- 消耗的系统资源较少。
对于大文件的传输,可以使用tqdm库来显示传输进度和剩余时间。以下是一个示例代码:
```python
import socket
import tqdm
import os
# TCP传输
def send_file_tcp(filename, host, port):
# 创建TCP连接
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
# 获取文件大小
filesize = os.path.getsize(filename)
# 发送文件名和大小
s.send(f"{filename} {filesize}".encode())
# 打开文件并逐步发送
with open(filename, "rb") as f:
progress = tqdm.tqdm(range(filesize), f"Sending {filename}", unit="B", unit_scale=True, unit_divisor=1024)
for _ in progress:
bytes_read = f.read(1024)
if not bytes_read:
break
s.sendall(bytes_read)
progress.update(len(bytes_read))
# 关闭连接
s.close()
# UDP传输
def send_file_udp(filename, host, port):
# 创建UDP连接
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 获取文件大小
filesize = os.path.getsize(filename)
# 发送文件名和大小
s.sendto(f"{filename} {filesize}".encode(), (host, port))
# 打开文件并逐步发送
with open(filename, "rb") as f:
progress = tqdm.tqdm(range(filesize), f"Sending {filename}", unit="B", unit_scale=True, unit_divisor=1024)
for _ in progress:
bytes_read = f.read(1024)
if not bytes_read:
break
s.sendto(bytes_read, (host, port))
progress.update(len(bytes_read))
# 关闭连接
s.close()
# 测试
filename = "test.pdf"
host = "localhost"
port = 1234
send_file_tcp(filename, host, port)
send_file_udp(filename, host, port)
```
这个代码中,我们使用了tqdm库来显示传输进度和剩余时间。在每次发送数据时,我们都会更新进度条的状态。
相关推荐
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)