Search code examples
javahttpserver

Java HttpServer and HttpHandler and URLConnection keep-alive


I have HttpServer with code

HttpServer server;
server = HttpServer.create(new InetSocketAddress(proxyConfig.port), 0);
server.setExecutor(java.util.concurrent.Executors.newCachedThreadPool());
server.createContext("/", new SMPBClientHandler());
server.start();

and SMPBClientHandler part of code:

public class SMPBClientHandler implements HttpHandler {
  @Override
  public void handle(final HttpExchange exchange) throws IOException {
    //Some code work with data
    exchange.close();
  }
}

On client side have connection

 HttpURLConnection retHttpURLConnection = (HttpURLConnection) urlToConnect.openConnection();
        retHttpURLConnection.setRequestMethod("POST");
//Some work code and then 
os = connection.getOutputStream();
//Some work with response
os.close();

But when i use exchange.close(); connection closing each time and then i do retHttpURLConnection.openConnection() on server side calls handle(final HttpExchange exchange) function.

How to create keep-alive connection?

I want one user=one connection.

now i got one user=many connection.


Solution

  • Shouldn't you be closing the response output stream on the server side, rather than the exchange itself?

    i.e.

    public class SMPBClientHandler implements HttpHandler {
        @Override
        public void handle(final HttpExchange exchange) throws IOException {
            OutputStream os = exchange.getResponseBody();
            os.write("response".getBytes());
            os.close();
        }
    }
    

    And on client-side

    HttpURLConnection retHttpURLConnection = (HttpURLConnection) urlToConnect.openConnection();
    retHttpURLConnection.setRequestMethod("POST");
    retHttpURLConnection.setRequestProperty("Connection", "keep-alive");
    //Some work code and then 
    os = connection.getOutputStream();
    //Some work with response
    os.close();