我有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();连接每次关闭然后我在服务器端调用httpHttpURLConnection.openConnection()调用句柄(最终的HttpExchange交换)函数。
如何创建keep-alive连接?
我想要一个用户=一个连接。
现在我有一个用户=很多连接。
答案 0 :(得分: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();