PrintWriter out = new PrintWriter(DoDSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(DoDSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null)
{
System.out.println(fromServer);
if ((fromUser= stdIn.readLine()) != null)
{
//System.out.println(fromUser);
out.println(fromUser);
}
}
在这个客户端代码中,我创建了一个Print Writer和一个与服务器通信的缓冲读取器,我还有一个单独的读取器,它从命令行读取System.in。
我目前的问题是,如果服务器向客户端发送多行字符串,我将按Enter键接收每一行。如何编辑此代码,以便在检查用户键入的内容之前从服务器的缓冲读取器打印每一行,而不是在每一行之后进行检查?
答案 0 :(得分:1)
为什么不在另一个循环之后做一个循环?:
PrintWriter out = new PrintWriter(DoDSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(DoDSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null)
{
System.out.println(fromServer);
}
while ((fromUser = stdIn.readLine()) != null)
{
System.out.println(fromUser);
}