0

Если создать Formatter из сокетного OutputStream-a, то .format() не отрабатывает как ожидается:

Server:

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(12345);
        Socket client = serverSocket.accept();
        Scanner scan = new Scanner(client.getInputStream());
        if (scan.hasNextLine()) {
            System.out.println(scan.nextLine());
        }
    }
}

Client:

import java.io.IOException;
import java.net.Socket;
import java.util.Formatter;

public class Client {

    public static void main(String[] args) throws IOException {
        // Этот кусок работает:
        Formatter stdOutFormatter = new Formatter(System.out);
        stdOutFormatter.format("My name is %s. I am %d years old.", "Test", 99);

        Socket s = new Socket("localhost", 12345);
        // А этот - нет:
        Formatter socketFormatter = new Formatter(s.getOutputStream());
        socketFormatter.format("My name is %s. I am %d years old.", "Alex", 43);
    }
}

1 ответ 1

1

Вам необходимо добавить flush() после отправки сообщения

public class Client {

    public static void main(String[] args) throws IOException {
        // Этот кусок работает:
        Formatter stdOutFormatter = new Formatter(System.out);
        stdOutFormatter.format("My name is %s. I am %d years old.", "Test", 99);

        Socket s = new Socket("localhost", 12345);
        // А этот - нет:
        Formatter socketFormatter = new Formatter(s.getOutputStream());
        socketFormatter.format("My name is %s. I am %d years old.", "Alex", 43);
        socketFormatter.flush(); // эта линия была добавлена
    }
}

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки