PrintWriter println(String s) method: \r\n not supported?
-
12-12-2019 - |
Question
I'm creating a multithread chat client server application. In the server connection I use PrintWriter println(String s) method to write the response to the client.
PrintWriter out;
String msg = in.readLine();
String response = "";
if (msg.startsWith("nick: ") {
response = protocol.authenticate(msg); //returns a String that says "welcome " + nick
//if there are messages pending for the author who logged in add them to the response String
response+="\r\n"+textmsg;
} else { ... }
out.println(response);
When I run the client, who uses the BufferedReader readLine() method to read from the server, I get the welcome message but not the pending message for the client, but If I use
response+=textmsg;
it works, so I assume it's because I'm using \r\n but I still need to print a new line between those two messages. What should I do?
Edit after accepting the answer: In the end I chose to use OutputStream and InputStream so I can send every kind of string I want, even with \r\n.
Solution
Either call println
once for each line of output (so twice) or use only \n
, without the \r
. That's Java's standard newline char and \r\n
is a Windows-specific end-of-line sequence. Of course, at the client end you now have to call readLine
twice as well. There is no way to call readLine
once and get two lines. If you need a custom delimiter, then you must use something else, not \n
.
OTHER TIPS
Use println with PrintWriter, for the \n.
use println
or use %n
with printf