【问题标题】:How to send file in python over network without loosing data?如何通过网络在python中发送文件而不丢失数据?
【发布时间】:2021-06-27 21:10:04
【问题描述】:

我正在尝试使用 Python 中的 2 个文件,一个名为 server.py 的文件通过我的网络发送包含此单词 'hello world' 的文件 data.txt

import socket
import tqdm
import os

# device's IP address
SERVER_HOST = "0.0.0.0"
SERVER_PORT = 5001
# receive 4096 bytes each time
BUFFER_SIZE = 4096
SEPARATOR = "<SEPARATOR>"

# create the server socket
# TCP socket
s = socket.socket()

# bind the socket to our local address
s.bind((SERVER_HOST, SERVER_PORT))

# enabling our server to accept connections
# 5 here is the number of unaccepted connections that
# the system will allow before refusing new connections
s.listen(5)
print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")

# accept connection if there is any
client_socket, address = s.accept() 
# if below code is executed, that means the sender is connected
print(f"[+] {address} is connected.")

# receive the file infos
# receive using client socket, not server socket
received = client_socket.recv(BUFFER_SIZE).decode()
filename, filesize = received.split(SEPARATOR)
# remove absolute path if there is
filename = os.path.basename(filename)
# convert to integer
filesize = int(filesize)

# start receiving the file from the socket
# and writing to the file stream
progress = tqdm.tqdm(range(filesize), f"Receiving {filename}", unit="B", unit_scale=True, unit_divisor=1024)
with open(filename, "wb") as f:
    while True:
        # read 1024 bytes from the socket (receive)
        bytes_read = client_socket.recv(BUFFER_SIZE)
        if not bytes_read:    
            # nothing is received
            # file transmitting is done
            break
        # write to the file the bytes we just received
        f.write(bytes_read)
        # update the progress bar
        progress.update(len(bytes_read))

progress.close()
# close the client socket
client_socket.close()
# close the server socket
s.close()

另一个叫client.py

import socket
import tqdm
import os

SEPARATOR = "<SEPARATOR>"
BUFFER_SIZE = 4096 # send 4096 bytes each time step

# the ip address or hostname of the server, the receiver
host = "192.168.1.12"

# the port, let's use 5001
port = 5001

# the name of file we want to send, make sure it exists
filename = "data.txt"

# get the file size
filesize = os.path.getsize(filename)

# create the client socket
s = socket.socket()

print(f"[+] Connecting to {host}:{port}")
s.connect((host, port))
print("[+] Connected.")

# send the filename and filesize
s.send(f"{filename}{SEPARATOR}{filesize}".encode())

# start sending the file
progress = tqdm.tqdm(range(filesize), f"Sending {filename}", unit="B", unit_scale=True, unit_divisor=1024)
with open(filename, "rb") as f:
    while True:
        # read the bytes from the file
        bytes_read = f.read(BUFFER_SIZE)
        if not bytes_read:
            # file transmitting is done
            break
        # we use sendall to assure transimission in 
        # busy networks
        s.sendall(bytes_read)
        # update the progress bar
        progress.update(len(bytes_read))
# close the socket
s.close()

这是我尝试过的:

我一遍又一遍地检查代码是否有任何错误。问题是虽然文件在发送之前包含一个字符串,但接收到的文件是 0 字节的空文件。

我该如何解决这个问题,任何帮助或建议将不胜感激。

【问题讨论】:

  • 下定决心。 '文件是空的,0字节'“它在开头包含一个字符串'?你不能同时拥有它。
  • 我刚刚更正了,那是一个拼写错误:),但还是谢谢。

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


【解决方案1】:

您似乎在同一目录中运行服务器和客户端,并且服务器在客户端读取文件之前截断了文件。

【讨论】:

    【解决方案2】:

    它适用于我的 hello world,但如果你想发送二进制文件,也许你可以尝试 base 64

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-16
      • 2015-06-23
      相关资源
      最近更新 更多