Java HttpServer 和 HttpHandler 以及 URLConnection 保持 Activity 状态

标签 java httpserver

我有带有代码的 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/

相关文章:

python - 如何停止作为 Windows 服务运行的 web.py 服务器

node.js - nodejs 和 socket.io.js 路径解析

java - 如何使用带有用户、组和权限的简单权限系统的 JPA?

c++ - 根据 http 请求确定服务器类型

java - 如何从多个来源填充一个ListView?

java - 在 Android 中运行的应用程序中存储数据的最佳选择 [SQLite 之前]

带有 httpServer 的 Java 应用程序在退出前挂起 45 秒

iphone - 我使用哪些类来使 iPhone 充当服务器?

java - API 后端的应用程序修订版 'X' 与预期的 'Y' 不一样

java - 将 2 个数组列表添加到 1 个具有相同索引值的数组列表中