简体   繁体   中英

While loop in Java doesn't break when pressing Enter, when condition is a DataInputStream.isAvailable() == 0 and the application runs with telnet

I am trying to simulate a "ping" command in Java. I extracted only lines which I consider relevant for my question. So, when running this code, it is printed "Pinging..." once per second, until the user presses ENTER. After ENTER is pressed, it is printed in console "Exit ping." and the application stops. The problem is when the application runs using telnet, the button ENTER doesn't have any effect. Note: the entire application is an OSGi application, and it may run both using telnet or not using it, so in both cases I should have the same behaviour. It works fine only if telnet is not used.

    DataInputStream dis = new DataInputStream(System.in);
    System.out.println("Press Enter to stop.");
    while (dis.available() == 0) {
        System.out.println("Pinging...");
        Thread.sleep(1000);
    }
    System.out.println("Exit ping.");

If I add at the end of "while" loop

System.out.println(dis.available())

without telnet, it prints 0, and when ENTER is pressed it prints a value.= 0, With telnet, even if ENTER is pressed. the value is 0.

dis.available() will not actually check for user input its not a read.

You will need to actually wait for the user input on a separate thread as you want to continue the loop in the main thread. example below

import java.util.Scanner;

public class GeneralMain {
    private static boolean exit = false;

    public static void main(String[] args) throws InterruptedException {

        System.out.println("Press Enter to stop.");
        Thread t = new Thread(new ReadFromCmd());
        t.start();
        while (!exit) {
            System.out.println("Pinging...");
            Thread.sleep(1000);
        }
        System.out.println("Exit ping.");
    }

    static class ReadFromCmd implements Runnable {
        @Override
        public void run() {
            Scanner s = new Scanner(System.in);
            s.nextLine();
            exit = true;
        }
    }
}

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