linux利用python+socket库,实现一个数据文件的收发,能动态显示传输的比例
时间: 2024-02-05 16:11:16 浏览: 76
基于socket的文件传输
可以使用Python socket和os模块来实现文件的收发,同时使用tqdm库来动态显示传输比例。下面是一个简单的示例代码:
服务端代码:
```python
import socket
import os
from tqdm import tqdm
SERVER_HOST = '0.0.0.0'
SERVER_PORT = 8888
BUFFER_SIZE = 4096
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((SERVER_HOST, SERVER_PORT))
server_socket.listen(1)
print(f"Listening on {SERVER_HOST}:{SERVER_PORT}...")
client_socket, client_address = server_socket.accept()
print(f"{client_address[0]}:{client_address[1]} connected.")
# 接收文件名和文件大小
filename = client_socket.recv(BUFFER_SIZE).decode()
filesize = int(client_socket.recv(BUFFER_SIZE).decode())
# 使用tqdm显示传输进度
progress = tqdm(range(filesize), f"Receiving {filename}", unit="B", unit_scale=True, unit_divisor=1024)
# 接收文件数据并写入文件
with open(filename, "wb") as f:
while True:
data = client_socket.recv(BUFFER_SIZE)
if not data:
break
f.write(data)
progress.update(len(data))
print("File received successfully!")
client_socket.close()
server_socket.close()
```
客户端代码:
```python
import socket
import os
from tqdm import tqdm
SERVER_HOST = 'localhost'
SERVER_PORT = 8888
BUFFER_SIZE = 4096
filename = input("Enter filename: ")
# 获取文件大小
filesize = os.path.getsize(filename)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((SERVER_HOST, SERVER_PORT))
# 发送文件名和文件大小
client_socket.send(filename.encode())
client_socket.send(str(filesize).encode())
# 使用tqdm显示传输进度
progress = tqdm(range(filesize), f"Sending {filename}", unit="B", unit_scale=True, unit_divisor=1024)
# 发送文件数据
with open(filename, "rb") as f:
while True:
data = f.read(BUFFER_SIZE)
if not data:
break
client_socket.sendall(data)
progress.update(len(data))
print("File sent successfully!")
client_socket.close()
```
在运行客户端和服务端代码之前,需要先安装tqdm库:
```
pip install tqdm
```
以上代码只是一个简单的示例,实际使用时可能需要进行优化和处理一些异常情况。
阅读全文