Home > Mobile >  Java shutdown http server after receiving request
Java shutdown http server after receiving request

Time:02-23

I have a setup a simple http server in java that only deals with one type of post request.

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:

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?

CodePudding user response:

What's wrong with calling server.stop(delay), where the delay is small enough (0 or 1)? You'll need to pass server as argument to the echoPost constructor.

CodePudding user response:

Use

System.exit(0);

It doesn't matter where this line of code is executed, it will terminate the JVM and quit.

  • Related