简体   繁体   English

Java 收到请求后关闭 http 服务器

[英]Java shutdown http server after receiving request

I have a setup a simple http server in java that only deals with one type of post request.我在 java 中设置了一个简单的 http 服务器,它只处理一种类型的发布请求。

The server code:服务器代码:

int port = 5555;
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
System.out.println("server started at " + port);
server.createContext("/echoPost", new echoPost());
server.setExecutor(null);
server.start();

The echoPost() class: echoPost() class:

public class echoPost implements HttpHandler {

    @Override
    public void handle(HttpExchange http) throws IOException {  
            
            
            InputStreamReader inputStreamReader = new InputStreamReader(http.getRequestBody(), "utf-8");
            BufferedReader bufferReader = new BufferedReader(inputStreamReader);
            String incoming = br.readLine();
            System.out.println(incoming);                         
            
            String response = "response";
            
            http.sendResponseHeaders(200, response.length());
            OutputStream outputStream = http.getResponseBody();
            os.write(response.toString().getBytes());
            os.close();
            
    }
}

I want the server to stop after a post request is received.我希望服务器在收到发布请求后停止。 Is there a way to do this so straight after one post request is handled the server stops?有没有一种方法可以在处理完一个发布请求后直接执行此操作,服务器停止?

What's wrong with calling server.stop(delay) , where the delay is small enough (0 or 1)?调用server.stop(delay)有什么问题,延迟足够小(0 或 1)? You'll need to pass server as argument to the echoPost constructor.您需要将server作为参数传递给echoPost构造函数。

Use利用

System.exit(0);

It doesn't matter where this line of code is executed, it will terminate the JVM and quit.不管这行代码执行到哪里,都会终止JVM并退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM