我正在使用 Python 套接字来接收文件。但是,有时我会收到以下错误:
Traceback (most recent call last):
File "C:\Users\Sharkoon\Nextcloud\Elektronik\pythonProject\main.py", line 54, in receive_File
received = client_socket.recv(BUFFER_SIZE).decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x94 in position 34: invalid start byte
Process finished with exit code 1
这发生在代码的第 4 到第 9 次执行时。难道是我在文件完全发送之前尝试解码?
代码如下:
# device's IP address
SERVER_HOST = "0.0.0.0"
SERVER_PORT = 1337
# receive 4096 bytes each time
BUFFER_SIZE = 4096
SEPARATOR = "<SEPARATOR>"
def receive_File():
# create the server socket
# TCP socket
s = socket.socket()
# bind the socket to our local address
s.bind((SERVER_HOST, SERVER_PORT))
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))
# close the server socket
s.close()
return filename
我正在使用的代码来自这里:https://www.thepythoncode.com/article/send-receive-files-using-sockets-python https://www.thepythoncode.com/article/send-receive-files-using-sockets-python