Search code examples
javaconsolecommandserversocket

java thread System.in how can i "wait for console commands"


Let's say I got System.in

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

result = br.readLine();
                while (!result.isEmpty()) {
                    if (result.equalsIgnoreCase("exit")) {
                        userStr="exit";
                        System.exit(0);
                    } else if (result.equalsIgnoreCase("list")) {
                        userStr="list";
                    } else if (result.equalsIgnoreCase("kill")) {
                        userStr="kill";
                    } else if (result.equalsIgnoreCase("help")) {
                        userStr="help";
}

and

ServerSocket socketListener = new ServerSocket(port);
while (true) {
                Socket client = socketListener.accept();
                new ServerThread(client,userStr); //pass userStr to Thread               
            }

i don't understand how can i "wait for console commands" and pass them to active Thread. I need to accept() clients, pass them to thread. If I entered a command into the server console like for example; "kill Username"(disconnect user) or "list"(list of Usernames) my server should pass commands to threads.

p/s I need manage server, manage implemented by entering the console commands.


Solution

  • As easy solution you can block you thread untill it will recieve a task to execute :

    class Task implements Runnable {
        AtomicReference<String> atomicReference = new AtomicReference<String>(null);
    
        @Override
        public void run() {
            while (true) {
                String command = atomicReference.getAndSet(null);
                if (command != null) {
                    //do staff with command
                }
            }
        }
    
        public void executeCommand(String command) {
            atomicReference.set(command);
        }
    }
    

    Use it like this:

    ServerSocket socketListener = new ServerSocket(port);
    Task task = new Task();
    new Thread(task).start();
    
    while (true) {
                Socket client = socketListener.accept();
                task.executeCommand(userCommand);
            }
    

    But if you need more complex solution I can advice you to read about Java Concurrency package:

    Avesome book about that

    Good article