我有以下Server.java

public class Main {
    public static void main(String args[]) throws Exception{
        ServerSocket server = new ServerSocket(12345);
        Socket client = server.accept();
        OutputStream out = client.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new PrintWriter(out));
        writer.write("Hello client");
        writer.flush(); //After executing of that instruction there is no any output on the client
        client.close(); //The client prints "Hello client"
    }
}


Client.java

public class Main {
    @SuppressWarnings("resource")
    public static void main(String args[]) throws Exception{
        Socket s = new Socket("localhost", 12345);
        BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
        System.out.println(r.readLine());
        s.close();
    }
}


问题是我无法理解为什么客户端仅在关闭连接后才打印字符串,而不是在刷新流之后才打印字符串的原因。我以为flush()向客户端发送信号,表明数据传输过程已结束。因为,客户端必须在调用flush()之前读取发送给它的所有数据。怎么了?

最佳答案

readLine()读取整行。要知道行已完成,读者需要找到换行符序列或流的末尾。因此它阻塞直到看到其中之一。

请意识到您的客户可能会很好地执行以下操作:

out.write("Hello ");
out.flush();
out.write("world!\n");
out.flush();


这将发送一行:“ Hello world”。顾名思义,readLine()应该返回该行,而不是两行“ Hello”和“ World”。

因此,如果要发送线路,则需要结束其线路终止符。否则,您不会发送一行,而只会发送一些字符。

请注意,如果正确使用了PrintWriter,它将更加容易:

PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())));
out.println("Hello client");

关于java - BufferedReader仅在关闭连接后才读取行,而在flush()之后不行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26880417/

10-10 14:57