首页 > 解决方案 > 如何使用 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!')

标签: pythonsocketsconcurrencychecksum

解决方案


推荐阅读