[英]Reading multiple lines from server
我对其他方法持开放态度,但这是我的代码:
public class Client {
public static void main (String [] args) {
try(Socket socket = new Socket("localhost", 7789)) {
BufferedReader incoming = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter outgoing = new PrintWriter(socket.getOutputStream(),true);
StringBuilder sb = new StringBuilder();
Scanner scanner = new Scanner(System.in);
String send = "";
String response = "";
while (!send.equals("logout")){
System.out.println("Enter Command: ");
send = scanner.nextLine();
outgoing.println(send);
while ((response = incoming.readLine()) != null) {
System.out.println(response);
sb.append(response);
sb.append('\n');
}
}
} catch (IOException e) {
System.out.println("Client Error: "+ e.getMessage());
}
}
}
我确实得到了服务器的响应,但是程序卡在了内部 while 循环中while ((response = incoming.readLine()) != null)
,所以我无法输入第二个命令。 如果传入的响应完成,我该如何打破循环?
问题在于,如果套接字关闭,则incoming.readLine()
只会返回null
,否则它将阻塞并等待来自服务器的更多输入。
如果您可以更改服务器,您可以添加一些标记,表明请求已被完全处理,然后像这样检查它while ((response = incoming.readLine()) != "--finished--")
。
如果你不能,试试这个:
while(response.isEmpty()){
if(incoming.ready()){ //check if there is stuff to read
while ((response = incoming.readLine()) != null){
System.out.println(response);
sb.append(response);
sb.append('\n');
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.