简体   繁体   中英

Break while loop on condition changed by action listener

I have made a server in Java and implemented a GUI for it. On the GUI there are two buttons - 'Allow' and 'Reject' connections. When 'Allow' is clicked the boolen value 'AllowConnections' is set to true and for 'Reject' it is set to false.

Basically the program will initialise the gui and the actionlisteners then if AllowConnections is true a socket will be opened and allow a client to connect to it. I am wanting to be able to click 'Reject' and it kick the user off the socket. The problem is that I cannot break out of the loop which constantly gets the incoming messages as it will pause and wait for a user to connect or for a user to send a message. This is shown bellow:

server class:

boolean loop = true;

while (loop) {

    if (allowConnections == true) {
        remote.commands();
    }
    else {
        System.out.println("reject");
    }

}

remote class:

public static void commands() {

    try {

        serverSocket = new ServerSocket(serverPort);
        System.out.println("open");

        Socket clientSocket = serverSocket.accept();
        connected = true;

        System.out.println("connected");
        BufferedReader clientMessage = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

        String input;

        while (connected) {

            input = clientMessage.readLine();
            System.out.println(input);

            // do commands

        }

    }

    catch (IOException e) {
        e.printStackTrace();
    }

}

In the code above the program will pause and wait for a user to connect (line: 8) and also wait for a user to send a message (line: 18) which means I cannot just put a if(!allowConnections){break;} condition statement in to break the loop.

Any ideas on how I would break this loop as the condition changes (sort of like a while loop that constantly checks conditions) or how I could rewrite this to include the feature I need?

Make allowConnections static and public (or use a getter), then you can check it inside commands() method.

EDIT: Start a new thread which checks if allowConnections has changed and call _ serverSocket.close()_ in case it change the state.

ServerSocket has method setSoTimeout : https://docs.oracle.com/javase/7/docs/api/java/net/ServerSocket.html#setSoTimeout(int)

This can be used to avoid accept blocking infinite. As the documentation states, if the time has been passed without a connection it will throw a java.net.SocketTimeoutException

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