Java HttpServer和HttpHandler以及URLConnection保持活跃

问题描述 投票:0回答:1

我有HttpServer代码

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

和SMPBClientHandler代码的一部分:

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

在客户端有连接

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

但是当我使用exchange.close();连接每次关闭然后我在服务器端调用handle(最终的HttpExchange交换)函数执行retHttpURLConnection.openConnection()。

如何创建keep-alive连接?

我想要一个用户=一个连接。

现在我有一个用户=很多连接。

java httpserver
1个回答
1
投票

你不应该关闭服务器端的响应输出流,而不是交换本身吗?

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

在客户端

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();
© www.soinside.com 2019 - 2024. All rights reserved.