我正在构建一个客户端/服务器应用程序,并尝试使用 PrintWriter 从服务器线程向客户端发送字符串。我像这样构造我的 PrintWriter:
// Instantiate a PrintWriterwith a correctly implemented
// client socket parameter, and autoflush set to true
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
进一步假设客户端正在使用 BufferedReader 从输入流中读取数据,实例化如下:
BufferedReader in = new BufferedReader(new InputStreamReader(client.server.getInputStream()));
客户端从服务器获取消息:
String serverMessage = in.readLine();
如您所见,我已将自动刷新设置为 true。现在假设我想向客户发送一条简单的消息。如果我执行语句:
out.println("给客户端的消息");
则消息发送成功。但是,如果我执行该语句:
out.print("Message to client");
那么消息就不会发送。另外:
out.print("Message to client");
out.flush();
也不起作用。
这是一个问题,因为我需要向终端中的客户端发送消息,并让他们能够在同一行上响应。如何使用 PrintWriter 发送消息,以便将其刷新/发送到客户端,但不发送换行符?
最佳答案
就您而言,您似乎正在使用 BufferedReader#readLine()
它将读取字符,直到到达换行符或到达流末尾,同时阻塞。因此,您需要服务器来写入新行字符。
另一种方法是直接读取字节,而不是依赖 BufferedReader#readLine()
。
why doesn't using a carriage return work?
换行符取决于系统。在 Windows 上,它是 \r\n
。在 Linux 上是 \n
。你可以通过
System.getProperty("line.separator")
但是您需要获取服务器的。
关于java - PrintWriter 仅使用 println 发送字符串而不打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22032666/