Приятно видеть чей-то фиксированный код!

аюсь отправить файлы с сервера Python на клиент Java через сокет TCP. Вот что у меня так далеко:

Клиент Java (обратите внимание, что весь код передачи файлов находится в методе getFile ()):

public class Client1
{
    private Socket socket = null;
    private FileOutputStream fos = null;
    private DataInputStream din = null;
    private PrintStream pout = null;
    private Scanner scan = null;

    public Client1(InetAddress address, int port) throws IOException
    {
        System.out.println("Initializing Client");
        socket = new Socket(address, port);
        scan = new Scanner(System.in);
        din = new DataInputStream(socket.getInputStream());
        pout = new PrintStream(socket.getOutputStream());
    }

    public void send(String msg) throws IOException
    {
        pout.print(msg);
        pout.flush();
    }

    public void closeConnections() throws IOException
    {
        // Clean up when a connection is ended
        socket.close();
        din.close();
        pout.close();
        scan.close();
    }

    // Request a specific file from the server
    public void getFile(String filename)
    {
        System.out.println("Requested File: "+filename);
        try {
            File file = new File(filename);
            // Create new file if it does not exist
            // Then request the file from server
            if(!file.exists()){
                file.createNewFile();
                System.out.println("Created New File: "+filename);
            }
            fos = new FileOutputStream(file);
            send(filename);

            // Get content in bytes and write to a file
            int counter;
            byte[] buffer = new byte[8192];
            while((counter = din.read(buffer, 0, buffer.length)) != -1)
            {
                fos.write(buffer, 0, counter);
            }                }
            fos.flush();
            fos.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

И сервер Python:

import socket

host = '127.0.0.1'
port = 5555

# Create a socket with port and host bindings
def setupServer():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("Socket created")
    try:
        s.bind((host, port))
    except socket.error as msg:
        print(msg)
    return s


# Establish connection with a client
def setupConnection():
    s.listen(1)     # Allows one connection at a time
    print("Waiting for client")
    conn, addr = s.accept()
    return conn


# Send file over the network
def sendFile(filename, s):
    f = open(filename, 'rb')
    line = f.read(1024)

    print("Beginning File Transfer")
    while line:
        s.send(line)
        line = f.read(1024)
    f.close()
    print("Transfer Complete")


# Loop that sends & receives data
def dataTransfer(conn, s, mode):
    while True:
        # Send a File over the network
        filename = conn.recv(1024)
        filename = filename.decode(encoding='utf-8')
        filename.strip()
        print("Requested File: ", filename)
        sendFile(filename, s)
        break
    conn.close()


s = setupServer()
while True:
    try:
        conn = setupConnection()
        dataTransfer(conn, s, "FILE")
    except:
        break

Мне удалось успешно создать программу обмена сообщениями между сервером и клиентом, где они передавали строки друг другу. Тем не менее, я не смог передать файлы по сети.

Похоже, что сервер Python отправляет байты должным образом, поэтому проблема со стороны Java. В частности, цикл while:while((counter = din.read(buffer, 0, buffer.length)) != -1) давал вывод-1 таким образом, запись файла фактически никогда не происходит.

Заранее спасибо за помощь!

Ответы на вопрос(1)

Ваш ответ на вопрос