java应用程序在调用终止方法后不会停止[关闭]

问题描述 投票:0回答:1

我编写了一段代码,用于读取本地 JSON 文件并将其放在端口 9000 上。在设定的时间限制后,类 PutJsonOnline 应终止。将调用终止方法并切断对端口 9000 的访问。但是,调用终止方法后,我仍然可以访问端口 9000。有人可以帮助我正确终止与端口 9000 的连接吗?


    private static volatile boolean isRunning = false;
    private static final CountDownLatch latch = new CountDownLatch(1);
    private static Thread serverThread;

    public static void main(String[] args) {
        startServer();
    }

    public static void startServer() {
        serverThread = new Thread(() -> {
            port(9000);

            // Define endpoint to serve JSON data
            get("/data", (req, res) -> {
                if (!isRunning) {
                    halt(403, "Server is not running");
                }
                res.type("application/json");

                // Read JSON data from file in resources directory
                InputStream inputStream = SendJsonToServer.class.getResourceAsStream("/data.json");
                String json = readFromInputStream(inputStream);

                return json;
            });

            // Log server start
            System.out.println("Server started on port 9000");
            isRunning = true;
            latch.countDown(); // Signal that the server has started
        });

        System.out.println("Starting server thread...");
        serverThread.start();
        try {
            latch.await(); // Wait for the server to start
            System.out.println("Server thread started and latch released.");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    private static String readFromInputStream(InputStream inputStream) {
        if (inputStream != null) {
            try (Scanner scanner = new Scanner(inputStream).useDelimiter("\\A")) {
                return scanner.hasNext() ? scanner.next() : "{}"; // Return empty JSON object if file is empty
            }
        }
        return "{}"; // Return empty JSON object if file is not found
    }

    public static void terminate() {
        System.out.println("Terminating server...");
        isRunning = false;

        // Stop the Spark server
        stop();

        // Wait for Spark to stop
        awaitStop();

        // Ensure the server thread is stopped
        if (serverThread != null && serverThread.isAlive()) {
            serverThread.interrupt();
            try {
                serverThread.join();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }

        System.out.println("Server stopped.");
    }
}
and this is how i call the terminate method:
`
private void terminateSendJsonToServer() {
        monitor.info("Terminating SendJsonToServer due to elapsed time constraint.");
        try {
            SendJsonToServer.terminate(); // Call the terminate method in SendJsonToServer class
            monitor.info("Called terminate method in SendJsonToServer.");
        } catch (Exception e) {
            // Handle any exceptions
            monitor.warning("Error terminating SendJsonToServer: " + e.getMessage());
            e.printStackTrace();
        }
    }
`
java server port terminate
1个回答
0
投票

我不知道你在哪里调用终止方法。如果我理解正确的话,你想等到

x
时间单位过去然后调用它,对吗? 这篇 Baeldung 文章 可能会满足您的需要。

© www.soinside.com 2019 - 2024. All rights reserved.