【问题标题】:Receive multiple files simultaneously同时接收多个文件
【发布时间】:2021-03-28 11:21:12
【问题描述】:

我在 Python 3.8.6 中编写了一个脚本,用于在不同设备之间发送和接收文件。我正在正常发送和接收文件,当我从不同设备接收多个同时连接时会出现问题。

我将脚本配置为将文件保存在以发送文件的设备地址命名的文件夹中,发生的情况是,当多个设备同时发送文件时,来自一个设备的文件会随机转到另一个文件夹.文件混合在一起。

我知道为什么会发生,但不知道如何解决。

我认为作为一种替代方法,一次只接收一个连接。 但我不知道该怎么做。

发送文件.py

def conectividade(host="192.168.0.13", porta=1218, timeout=5):
while True:
    try:
        socket.setdefaulttimeout(timeout)
        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, porta))
        return True
    except Exception:
        return False


# Function that sends the collected data.
def coleta():
total = []
conectividade()
conect = conectividade()
if conect == False:
    print("\nConnectivity is",conect)
    pass
else:
    data_hoje = datetime.now().strftime('%Y-%b-%d')
    direct = f".\\{data_hoje}\\"
    arquivos = os.listdir(direct)
    for arquivo in arquivos:
        try:
            sock = socket.socket()
            host = "192.168.0.13"
            porta = 1218
            print("Connectivity is", conect)
            sock.connect((host, porta))
            total += arquivo.split(',')
            sock.send(str.encode(arquivo))
            arquivo = str.encode(direct + arquivo)
            with open(arquivo, "rb") as file:
                data = file.read(1024)
                resposta = sock.recv(1024)
                if resposta == b'Waiting file':
                    file_size = os.path.getsize(arquivo)
                    print(b"sending " + arquivo)
                    print(file_size,"kb")
                    sock.send(bytes(str(file_size),'utf-8'))
                    resposta = sock.recv(1024)
                    if resposta == b'Waiting...':
                        while data:
                            sock.send(data)
                            data = file.read(1024)
                            if not data:
                                print(f"**Sending Complete**\n")
                                sock.close()
                        # Delete files after uploads
                        if total == arquivos:
                            print(f"Uploaded files:\n",total)


        except socket.error:
            print("\nSocket Error\n")

接收.py

data_hoje = datetime.now().strftime('%Y-%b-%d')
sock = socket.socket()
host ='192.168.0.13'
porta = 1218
sock.bind((host, porta))
sock.listen(10)
total = []
while True:
    conn, addr = sock.accept()
    pasta = ".\\" + addr[0].replace('.','_')
    subpasta = pasta + "\\" +  data_hoje
    if os.path.exists(pasta) == False:
        os.makedirs(f'{pasta}')
    if os.path.exists(subpasta) == False:
        os.makedirs(f'{subpasta}')
    data = conn.recv(1024)
    while data == b'':
        conn.close()
        conn, addr = sock.accept()
        data = conn.recv(1024)
    if data == b'Finalizando socket':
        print("Finalizando conexão com " + addr[0])
        conn.close()
        sock.close()
    total += data.decode().split(',')
    name_file = total[-1]
    with open(f"{subpasta}\\{name_file}", "wb") as file:
        conn.send(b"Waiting file")
        data = conn.recv(1024)
        tamanho = data.decode('utf-8')
        file_size = int(tamanho)
        if file_size != 0:
            conn.send(b"Waiting...")
            print("HOST <--> " + addr[0] + f"  Download de {name_file} - {tamanho} kb")
            while data:
                data = conn.recv(1024)
                file.write(data)
        
            conn.close()

【问题讨论】:

  • 您的receive.py 大多会丢弃它收到的数据,因此很难弄清楚它是如何工作的。在尝试修复代码之前,您应该阅读并理解 this 答案。

标签: python python-3.x sockets python-sockets


【解决方案1】:

基本上,导致错误的原因是原始脚本中递归的 conectividade() 函数。

所以我需要...

while True:
    conn.close()
    conn, addr = socket.accept()
    data = conn.recv

fzdb 所说的导致文件混合的原因...

新脚本怎么样...

发送文件.py

import socket
import os
from datetime import datetime

def coleta():
    total = []
    data_hoje = datetime.now().strftime('%Y-%b-%d')
    direct = f".\\{data_hoje}\\"
    arquivos = os.listdir(direct)
    for arquivo in arquivos:
        try:
            sock = socket.socket()
            host = "192.168.0.13"
            porta = 1218
            print("Connectivity is",)# conect)
            sock.connect((host, porta))
            total += arquivo.split(',')
            sock.send(str.encode(arquivo))
            arquivo = str.encode(direct + arquivo)
            with open(arquivo, "rb") as file:
                data = file.read(1024)
                resposta = sock.recv(1024)
                if resposta == b'Waiting file':
                    file_size = os.path.getsize(arquivo)
                    print(b"sending " + arquivo)
                    print(file_size,"kb")
                    sock.send(bytes(str(file_size),'utf-8'))
                    resposta = sock.recv(1024)
                    if resposta == b'Waiting...':
                        while data:
                            sock.send(data)
                            data = file.read(1024)
                            if not data:
                                sock.close()
                                print(f"**Sending Complete**\n")
                        if total == arquivos:
                            print(f"Uploaded files:\n",total)


    except socket.error:
        print("\nSocket Error\n")

接收.py

import socket
import os
from datetime import datetime

data_hoje = datetime.now().strftime('%Y-%b-%d')
host ='192.168.0.13'
porta = 1218
sock.bind((host, porta))
sock.listen(10)
total = []
while True:
    conn, addr = sock.accept()
    pasta = ".\\" + addr[0].replace('.','_')
    subpasta = pasta + "\\" +  data_hoje
    if os.path.exists(pasta) == False:
        os.makedirs(f'{pasta}')
    if os.path.exists(subpasta) == False:
        os.makedirs(f'{subpasta}')
   data = conn.recv(1024)
    if data == b'':
        conn.close()
    total += data.decode().split(',')
    name_file = total[-1]
    try:
        with open(f"{subpasta}\\{name_file}", "wb") as file:
            conn.send(b"Waiting file")
            data = conn.recv(1024)
            tamanho = data.decode('utf-8')
            file_size = int(tamanho)
            if file_size != 0:
                conn.send(b"Waiting...")
                print("HOST <--> " + addr[0] + f"  Download de {name_file} - {tamanho} bytes")
                while data:
                    data = conn.recv(1024)
                    file.write(data)
    except:
        pass

谢谢!

对于那些想要帮助原始代码的人......

我在 pynput 上使用 NumPad 时遇到问题

https://github.com/gconelhero/Keylogger

【讨论】:

    【解决方案2】:

    在receive.py 你有:

    conn, addr = sock.accept()
    # [...]
    while data == b'':
        conn.close()
        conn, addr = sock.accept()
        data = conn.recv(1024)
    

    在第一个accept() 上连接的客户端可能与循环内在accept() 上连接的客户端不同,这可能会导致文件像您描述的那样混淆。您应该使用单个accept() 重新编写它,以确保为同一个客户端完成整个处理。这种方法在TCP/IP Client and Server - PyMOTW-3 中有描述。

    修改receive.py:

    data_hoje = datetime.now().strftime("%Y-%b-%d")
    sock = socket.socket()
    host = "192.168.0.13"
    porta = 1218
    sock.bind((host, porta))
    sock.listen(10)
    total = []
    try:
        while True:
            conn, addr = sock.accept()
            try:
                pasta = ".\\" + addr[0].replace(".", "_")
                subpasta = pasta + "\\" + data_hoje
                if os.path.exists(pasta) is False:
                    os.makedirs(f"{pasta}")
                if os.path.exists(subpasta) is False:
                    os.makedirs(f"{subpasta}")
                data = b""
                while data == b'':
                    data = conn.recv(1024)
                if data == b"Finalizando socket":
                    print("Finalizando conexão com " + addr[0])
                    continue
                total += data.decode().split(",")
                name_file = total[-1]
                with open(f"{subpasta}\\{name_file}", "wb") as file:
                    conn.send(b"Waiting file")
                    data = conn.recv(1024)
                    tamanho = data.decode("utf-8")
                    file_size = int(tamanho)
                    if file_size != 0:
                        conn.send(b"Waiting...")
                        print(
                            "HOST <--> " + addr[0] + f"  Download de {name_file} - {tamanho} kb"
                        )
                        while data:
                            data = conn.recv(1024)
                            file.write(data)
    
            finally:
                conn.close()
    finally:
        sock.close()
    

    【讨论】:

    • 这段代码保留了原版的大部分bug。
    • fzdb,感谢您的想法,我查看了代码。当我在 sendfile.py 中放入函数 conectividade() 时,socket 错误破坏了脚本,在放入除了 socket.error 后,它不再发生,让我不再需要 conectividade...
    • @PresidentJamesK.Polk 随意详细说明,但请注意 OP 没有报告数据丢失,在某些时候只读取 1k 对他来说没问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 2022-09-29
    相关资源
    最近更新 更多