从服务器读取多行

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()只会return 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');
        }
    }
}