0

我有带有代码的 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(); 每次关闭连接,然后我在服务器端调用句柄(最终 HttpExchange 交换)函数时执行 retHttpURLConnection.openConnection()。

如何创建保持连接?

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

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

4

1 回答 1

1

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

IE

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();
于 2013-10-11T11:18:56.863 回答