python - 如何使用 Python 中的套接字编程从文件夹同时发送多个文件
问题描述
我是 Python 编程的新手。我想编写一个套接字程序,允许客户端将多个文件(并发)从文件夹发送到服务器。例如,客户端创建一个My Folder
包含 150 个文件的文件夹,并将并发 2、4 和 6 的文件从文件夹发送到服务器。即客户端一次向服务器发送2、4、6个文件,直到发送完150个文件。应用程序应该支持完整性验证,客户端和服务器计算每个文件的校验和并进行比较。但是现在,我的程序只将一个文件从客户端发送到服务器。
客户端.py
import hashlib
import socket
import tqdm
import os
SEPARATOR = "<SEPARATOR>"
BUFFER_SIZE = 25 * 1024
host = "127.0.0.1"
port = 5050
filename = "file\data.xlsx"
filename = hashlib.sha3_512().hexdigest()
filesize = os.path.getsize(filename)
s = socket.socket()
print(f"[+] Connecting to {host}:{port}")
s.connect((host, port))
print("[+] Connected.")
s.send(f"{filename}{SEPARATOR}{filesize}".encode())
progress = tqdm.tqdm(range(filesize), f"Sending {filename}", unit="B", unit_scale=True, unit_divisor=1024)
with open(filename, "rb") as f:
while True:
bytes_read = f.read(BUFFER_SIZE)
if not bytes_read:
break
s.sendall(bytes_read)
progress.update(len(bytes_read))
print('Successfully send the file')
s.close()
print('Connection Closed!')
服务器.py
import socket
import os
import tqdm
import threading
import hashlib
SERVER_HOST = "127.0.0.1"
SERVER_PORT = 5050
BUFFER_SIZE = 25 * 1024
SEPARATOR = "<SEPARATOR>"
s = socket.socket()
s.bind((SERVER_HOST, SERVER_PORT))
s.listen(5)
print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")
client_socket, address = s.accept()
print(f"[+] {address} is connected.")
rcv = client_socket.recv(BUFFER_SIZE).decode()
filename, filesize = rcv.split(SEPARATOR)
filename = os.path.basename(filename)
filesize = int(filesize)
progress = tqdm.tqdm(range(filesize), f"Receiving {filename}", unit="B", unit_scale=True, unit_divisor=1024)
with open(filename, "wb") as f:
while True:
bytes_read = client_socket.recv(BUFFER_SIZE)
if not bytes_read:
break
f.write(bytes_read)
progress.update(len(bytes_read))
client_socket.close()
print('File successfully received')
s.close()
print('Connection closed!')
解决方案
推荐阅读
- python - 匹配的查询不存在。Django 错误
- sql - SQL 在几个日期之前获取 count(*)
- tableau-api - 在 LOD 中使用 RANK:详细级别表达式不能包含表计算或 Tableau 中的 attr 函数
- php - Yajra Datatables 编辑打印布局
- python - 拟合多项式回归时形状未对齐
- c# - 如何使用 LIST 进行过滤
在 LINQ 中 - networking - What can be done to avoid hosts file entry?
- node.js - Import Express Routes causes Request Body to be Undefined
- windows - no sound difference with multiband compression plugin juce
- perl - 从 perl 脚本运行时,无法获取 wget 命令以将响应结果输出到文件