Search code examples
javasocketsprintwriter

Text moves to right when outputs to console PrintWriter


I'm coding a really simple server app, so when a client connects to it, it outputs an incrementing number from for-loop each second:

int port = 9428;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Waiting for client..");
Socket client = serverSocket.accept();
System.out.println("Client accepted!");
PrintWriter clientWriter = new PrintWriter(client.getOutputStream());

for (int i = 0; i < 10; i++) {
    clientWriter.write(i + "\n");
    clientWriter.flush();
    Thread.sleep(1000);
}

clientWriter.close();
client.close();

Although the program works fine, it aligns the output in the console in a weird way:

enter image description here

To connect to server, I use telnet in Windows console: telnet localhost 9428

I can't manage why it works in this way, I should be all aligned in one column, as it was done by System.out.println(i).

Anyone has the same issue and knows how to fix it?


Solution

  • You are on Windows so you must use Windows line end \r\n. You can get it from System.lineSeparator() instead of hardcoding.

    clientWriter.write(i + System.lineSeparator());
    

    or use PrintWriter.println(int) which will output the line separator after the value:

    clientWriter.println(i);