套接字OutputStream(BufferedWriter)不刷新消息

时间:2015-10-22 19:33:28

标签: java sockets outputstream flush

使用简单的客户端我尝试通过Socket OutputStream发送控制台输入:

try (Socket socket = new Socket(host, port);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {

    Thread input = new Thread(() -> {
        String msg;
        try {
            while ((msg = in.readLine()) != null) {
                System.out.println(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
    input.start();

    String msg;
    try {
        while ((msg = stdIn.readLine()) != null) {
            out.write(msg);
            out.flush(); // not flushing?
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

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

我似乎没有刷新流,直到我发送END OF INPUT之后我在服务器端接收所有先前的尝试作为一个长String,但也终止了客户端。 / p>

使用PrintWriter代替BufferedWriter会产生相同的结果。

为什么在从END OF INPUT读取std in(^ Z)之前数据不会消失?

1 个答案:

答案 0 :(得分:2)

你正在读行,但你不是在写行。在编写时,在邮件中添加行终止符。