JavaFX - How to close all running threads before exiting the application?

I created a Chat / Client Chat application with JavaFX. My ServerController creates a server object when the "Start Server" button is clicked, which starts in a separate thread.

Here is my problem:

Whenever I simply close the window with the default “x” Button, the server thread shuts down but does not inform the active Clients that the server is shut down. I need to tell Clients that the server is turned off, as I do with my Stop-Server button. My server contains a link to a controller object.

public class ServerController {

@FXML
TextArea chatEvent_txt;
@FXML
Button start_btn;
@FXML
Button stop_btn;
private Server server;
private boolean started = false;
private StringBuffer chatEvents = new StringBuffer("");

/**
 * @param e
 */
@FXML
public void startButtonAction(ActionEvent e) {
    if (!started) {
        this.server = new Server(this);
        new Thread(server).start();
        started = true;
        chatEvents = chatEvents.append("Server started.." + "\n");
        chatEvent_txt.setText(chatEvents.toString());
    } else {
        chatEvent_txt.setText("Server already started\n");
    }
}

Here is my "Stop-Server" button, which tells the whole client that the server will be shut down, and then closes all sockets, etc.

@FXML
public void stopButtonAction(ActionEvent e) {
    if (started) {
        server.setRunning(false);
        chatEvent_txt.setText("Server wurde gestoppt\n");
        started = false;
    }
}

setRunning(); false, while, . while , , , .

run-Method :

@Override
public void run() {
    try {
        serverSocket.setSoTimeout(500);
        while (running) {
            try {
                clientSocket = serverSocket.accept();
                new Thread(new Listener(clientSocket, this)).start();
            } catch (IOException e) {
            }
        }
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    try {
        broadcastMessage(new Message(Message.Type.DISCONNECT_OK, "Server"));
        serverSocket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

"x'-Button" , "Stop Server" -Button?

+4
1

@FXML
public void stopButtonAction(ActionEvent e) {
    shutdown();
}

public void shutdown() {
    if (started) {
        server.setRunning(false);
        chatEvent_txt.setText("Server wurde gestoppt\n");
        started = false;
    }
}

, FXML, :

FXMLLoader loader = new FXMLLoader(getClass().getResource("/path/to/fxml"));
Parent root = loader.load();
Scene scene = new Scene(root);
someStage.setScene(scene);

ServerController controller = loader.getController();
someStage.setOnCloseRequest(e -> controller.shutdown());

, (, , , ), e.consume() onCloseRequest.

+2

Source: https://habr.com/ru/post/1665766/


All Articles