简体   繁体   中英

PrintWriter println(String s) method: \r\n not supported?

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.

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 .

\\ n将println与PrintWriter一起使用。

使用println或将%nprintf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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