我编写了一段代码,用于读取本地 JSON 文件并将其放在端口 9000 上。在设定的时间限制后,类 PutJsonOnline 应终止。将调用终止方法并切断对端口 9000 的访问。但是,调用终止方法后,我仍然可以访问端口 9000。有人可以帮助我正确终止与端口 9000 的连接吗?
import static spark.Spark.*;
import java.io.InputStream;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
public class PutJsonOnline {
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.");
}
}