【问题标题】:HttpServer within junit fails with address in use error after first test第一次测试后,junit 中的 HttpServer 失败并出现地址使用错误
【发布时间】:2012-05-15 19:38:01
【问题描述】:

我有一个用于 JUnit 4.x 的 Java 类。在每个 @Test 方法中,我创建一个新的 HttpServer,使用端口 9090。第一次调用工作找到,但随后的错误“地址已在使用中:绑定”。

这是一个例子:

@Test
public void testSendNoDataHasValidResponse() throws Exception {
    InetSocketAddress address = new InetSocketAddress(9090);
    HttpHandler handler = new HttpHandler() {

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            byte[] response = "Hello, world".getBytes();
            exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
            exchange.getResponseBody().write(response);
            exchange.close();
        }
    };
    HttpServer server = HttpServer.create(address, 1);
    server.createContext("/me.html", handler);
    server.start();

    Client client = new Client.Builder(new URL("http://localhost:9090/me.html"), 20, "mykey").build();

    client.sync();
    server.stop(1);
    assertEquals(true, client.isSuccessfullySynchronized());
}

显然,HttpServer 仅在每个方法中保存,并在结束前停止。我看不到是什么继续保持任何套接字打开。第一次测试通过,后面的每次都失败。

有什么想法吗?

用更正的方法编辑:

@Test
public void testSendNoDataHasValidResponse() throws Exception {
    server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 1);
    HttpHandler handler = new HttpHandler() {

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            byte[] response = "Hello, world".getBytes();
            exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
            exchange.getResponseBody().write(response);
            exchange.close();
        }
    };
    server.createContext("/me.html", handler);
    server.start();
    InetSocketAddress address = server.getAddress();
    String target = String.format("http://%s:%s/me.html", address.getHostName(), address.getPort());

    Client client = new Client.Builder(new URL(target), 20, "mykey").build();

    client.sync();
    server.stop(0);
    assertEquals(true, client.isSuccessfullySynchronized());
}

【问题讨论】:

    标签: java junit com.sun.net.httpserver


    【解决方案1】:

    果冻的答案是钱。

    其他解决方法:

    【讨论】:

      【解决方案2】:

      在您重新绑定到特定端口号之前,通常需要等待 2 分钟。运行 netstat 以确认您的服务器的连接是否在 TIME_WAIT 中。如果是这样,您可以在绑定之前使用 SO_REUSEADDR 选项来绕过它。文档是here for java。

      【讨论】:

      • 我可以看到 - 感谢您的提示。现在,如果我在启动 HttpServer 时使用它,问题将得到解决......
      【解决方案3】:

      当你创建 HttpServer 时,你指定了

      允许的最大排队传入连接数 监听套接字

      这是1

      server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 1);
      

      link

      【讨论】:

        猜你喜欢
        • 2012-11-26
        • 2012-08-14
        • 1970-01-01
        • 2011-12-09
        • 2021-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-30
        相关资源
        最近更新 更多