0

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.

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.