简体   繁体   中英

Reading multiple lines from server

I'm open for other ways to do this, but this is my code:

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());
        }
    }
}

I do get response from the server, but the program is getting stuck in the inner while loop while ((response = incoming.readLine()) != null) , so i can't enter a second command. how do i break the loop if the incoming response is done ?

The problem is that incoming.readLine() will only return null if the socket is closed, otherwise it will block and wait for more input from the server.

If you can change the server, you could add some marking that the request was fully processed and then check it like this while ((response = incoming.readLine()) != "--finished--") .

If you cannot, try this:

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');
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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