Search code examples
javasocketswhile-loopbufferedreaderjava-io

While loop doesn't break after reading multiple line of text with BufferedReader in Java Socket


I have trying to send multiple lines of code from a client to the server.

Here is the code on the server side

            in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            out = new PrintWriter(client.getOutputStream(), true);

            //read client input
            //multi line 
            //https://stackoverflow.com/questions/43416889/java-filereader-only-seems-to-be-reading-the-first-line-of-text-document?newreg=2f77b35c458846dbb1290afce8853930
            String line = "";
            while((line =in.readLine()) != null) {
                System.out.println(line);
            }
            System.out.println("is it here?");

Here is the code on the client side :

    BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter out = new PrintWriter(socket.getOutputStream(),true);

    while (true) {
        System.out.print("> ");

        //content server input command (put, lamport clock, message)
        String command = keyboard.readLine();
        if (command.equals("quit")){
            break;
        }
        //read from CSDB/txt1.txt
        String message = readFileReturnString("CSDB/txt1.txt", StandardCharsets.UTF_8);
        System.out.println(message);
        //send to clientHandler through PrintWriter
        out.println(command + " 3 \n" + message);

        //receive response from ClientHandler (lamport clock)
        String serverResponse = input.readLine();
        System.out.println(serverResponse + socket);
    }

Server side is able to print out all the text that is sent from the client side. However, the while loop doesn't break and System.out.println("is it here?"); has never been executed.

May I know why and how I can solve this problem please?


Solution

  • @ talex Then you need to tell server when it should exit the loop. Yo may send special string or something.

    This works fine.

            String line = "";
            while((line =in.readLine()) != null) {
                System.out.println(line);
                if (line.equals("break") {
                break;
                }
            }