首页 > 解决方案 > 使用 Python Socket 分块发送和接收文件

问题描述

我正在尝试通过 Python 3.9 套接字发送和接收文件,但我的代码只工作了一半。

客户端(文件阅读器)的代码:

import socket

r = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
r.connect((socket.gethostname(), 8080))
with open("fileToRead.jpg", "rb") as fileReader:
    for data in fileReader:
        r.send(data)
    r.send("flag".encode())
print("I have finished reading")
userInp = ""
while userInp != "exit":
    userInp = input("Enter input: ")
r.close()

服务器的代码(文件编写器):

import socket
w = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
w.bind((socket.gethostname(), 8080))
w.listen(1)
conn, addr = w.accept()
print("Connection made from ", addr)

with open("fileToWrite.jpg", "wb") as fileWriter:
    while True:
        data = conn.recv(1024)
        if data.decode() == "flag":
            break
        fileWriter.write(data)
        print("just wrote data")
    print("I have finished writing")
while True:
    input("Test to see if I can work after file transfer: ")

传输文件后,我需要客户端和服务器仍然保持连接。我提供的代码只为我工作了一半,我不知道为什么。一半不工作,服务器卡在行print("just write data")

标签: pythonsocketsfile-transferchunkspython-3.9

解决方案


推荐阅读