我有带有代码的 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(final HttpExchange Exchange) 函数执行 retHttpURLConnection.openConnection() 。
如何创建保持 Activity 连接?
我想要一个用户=一个连接。
现在我有一个用户=多个连接。
最佳答案
您不应该关闭服务器端的响应输出流,而不是交换本身吗?
即
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();
关于Java HttpServer 和 HttpHandler 以及 URLConnection 保持 Activity 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19316644/