简体   繁体   English

PrintWriter println(String s)方法:\\ r \\ n不支持?

[英]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 println(String s)方法将响应写入客户端。

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 当我运行使用BufferedReader readLine()方法从服务器读取的客户端时,我收到欢迎消息,但未收到客户端的挂起消息,但是如果我使用

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. 它可以正常工作,所以我认为这是因为我使用的是\\ r \\ n,但是我仍然需要在这两条消息之间打印新行。 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. 接受答案后进行编辑 :最后,我选择使用OutputStream和InputStream,以便即使使用\\ r \\ n也可以发送所需的每种字符串。

Either call println once for each line of output (so twice) or use only \\n , without the \\r . 对输出的每一行调用一次println (如此两次),或者仅使用\\n ,而不使用\\r That's Java's standard newline char and \\r\\n is a Windows-specific end-of-line sequence. 这是Java的标准换行符char和\\r\\n是Windows特定的行尾序列。 Of course, at the client end you now have to call readLine twice as well. 当然,在客户端,您现在也必须两次调用readLine There is no way to call readLine once and get two lines. 无法调用一次readLine并获得两行。 If you need a custom delimiter, then you must use something else, not \\n . 如果需要自定义定界符,则必须使用其他名称,而不是\\n

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

使用println或将%nprintf

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

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