AXenos
AXenos

Reputation: 89

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 e.g. Hello World, it only prints Hello. It seems that readLine() method behaves like the line is terminated when reading white space.

Is it a character encoding issue or what? Any help would be much appreciated.

Upvotes: 1

Views: 186

Answers (1)

Thomas
Thomas

Reputation: 182093

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:

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

Naively, you might expect that you'd see Hello on the server immediately after you type the space. 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.

To read input line by line, you don't need a Scanner; simply wrap System.in in a BufferedReader and use its readLine() method.

Upvotes: 2

Related Questions