简体   繁体   English

Java socket readLine() 方法异常行为

[英]Java socket readLine() method strange behavior

I have the following code snippet in a socket server for testing.我在套接字服务器中有以下代码片段进行测试。

try (BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    PrintWriter out = new PrintWriter(client.getOutputStream(), true)){

    String input;
    while ((input = in.readLine()) != null) {
        if (input.equalsIgnoreCase("exit")) {
            System.out.println("Received `exit`... closing client " + client.getRemoteSocketAddress());
            break;
        }

        System.out.println("Received: " + input);
        out.println("OK");
    }
} catch(IOException e) {
    e.printStackTrace();
}

When i send a line to it with white space eg Hello World , it only prints Hello .当我用空白向它发送一行时,例如Hello World ,它只打印Hello It seems that readLine() method behaves like the line is terminated when reading white space.似乎readLine()方法的行为就像在读取空白时终止了行。

Is it a character encoding issue or what?是字符编码问题还是什么? Any help would be much appreciated.任何帮助将非常感激。

In the comments, you mentioned how you send the data:在评论中,您提到了如何发送数据:

Scanner keyboard = new Scanner(System.in);
out.println(keyboard.next());

And indeed the Scanner.next() call returns each word separately, as described in the documentation :实际上, Scanner.next()调用分别返回每个单词,如文档中所述

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace . Scanner使用分隔符模式将其输入分解为标记,默认情况下匹配空格

Naively, you might expect that you'd see Hello on the server immediately after you type the space.天真地,您可能希望在键入空格后立即在服务器上看到Hello That doesn't happen because the input stream is line-buffered by default, so the Scanner doesn't see any input until you press Enter.这不会发生,因为输入 ZF7B44CFFAFD5C52223D5498196C8A2E7BZ 默认情况下是行缓冲的,因此在您按 Enter 之前Scanner看不到任何输入。

To read input line by line, you don't need a Scanner ;要逐行读取输入,您不需要Scanner simply wrap System.in in a BufferedReader and use its readLine() method.只需将System.in包装在BufferedReader中并使用其readLine()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM