关闭java中的httpserver连接单击按钮

时间:2018-09-23 06:20:23

标签: java javafx network-programming

我用javafx编写了一个httpServer,在UI中创建了一个名为 startserver 的按钮,服务器通过单击该按钮启动,如何通过单击同一按钮来关闭套接字连接

@FXML
private void handleButtonAction(ActionEvent event) {
    try {
        HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080), 0);
        httpServer.createContext("/", new myhttpHandler());
        httpServer.setExecutor(null);
        httpServer.start();
    } catch (IOException ex) {
        Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

static class myhttpHandler implements HttpHandler {

    @Override
    public void handle(HttpExchange he) throws IOException {

        String requestMethod = he.getRequestMethod();
        if (requestMethod.equalsIgnoreCase("GET")) {

            int responseCode_OK = 200;
            String response = " my http server working ";
            he.sendResponseHeaders(responseCode_OK, response.length());
            OutputStream outputStream = he.getResponseBody();
            outputStream.write(response.getBytes());
            outputStream.close();
        }
        he.close();
    }

1 个答案:

答案 0 :(得分:0)

如果您需要启动和停止使用同一按钮,则ToggleButton可能会为您提供更好的服务。您可以检查切换状态是启动还是停止HttpServer。

否则,您需要检查服务器是否正在运行。

boolean isRunning ...
if (isRunning) {
    httpServer.stop();
} else {
    httpServer.start();
}