简体   繁体   English

在 Java 中,如何使用 HttpURLConnection 关闭连接并释放端口/套接字?

[英]In Java, how close the connection and free the port/socket using HttpURLConnection?

I'm using HttpURLConnection to do download of pages in Java.我正在使用 HttpURLConnection 下载 Java 中的页面。 I forgot to release the connections and I think this was causing some problems to my system (a webcrawler).我忘了释放连接,我认为这给我的系统(网络爬虫)造成了一些问题。

Now I've done some tests and see that after disconnecting, some connections still like TIME_WAIT in the results from the netstat command on Windows.现在我做了一些测试,发现断开连接后,Windows 上的netstat命令的结果中,一些连接仍然像 TIME_WAIT。

How I do to free this connection immediately?如何立即释放此连接?

Example code:示例代码:

private HttpURLConnection connection;

boolean openConnection(String url) {
    try {
        URL urlDownload = new URL(url);
        connection = (HttpURLConnection) urlDownload.openConnection();
        connection.setInstanceFollowRedirects(true);
        connection.connect();
        connection.disconnect();
        return true;
    } catch (Exception e) {
        System.out.println(e);
        return false;
    }
}

In some implementations, if you have called getInputStream or getOutputStream , you need to ensure that those streams are closed.在某些实现中,如果您调用了getInputStreamgetOutputStream ,则需要确保这些流已关闭。 Otherwise, the connection can stay open even after calling disconnect .否则,即使在调用disconnect之后,连接也可以保持打开状态。

EDIT:编辑:

This is from the J2SE docs for HttpURLConnection [emphasis added]:这是来自 HttpURLConnection 的J2SE 文档[强调添加]:

Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time.如果持续连接当时处于空闲状态,则调用 disconnect() 方法可能会关闭底层套接字。

And this is from the Android docs :这是来自Android 文档

To reduce latency, this class may reuse the same underlying Socket for multiple request/response pairs.为了减少延迟,这个 class 可以为多个请求/响应对重用相同的底层 Socket。 As a result, HTTP connections may be held open longer than necessary.因此,HTTP 连接的打开时间可能会超过必要的时间。 Calls to disconnect() return the socket to a pool of connected sockets.调用 disconnect() 将套接字返回到连接的 sockets 池。 This behavior can be disabled by setting the "http.keepAlive" system property to "false" before issuing any HTTP requests.在发出任何 HTTP 请求之前,可以通过将“http.keepAlive”系统属性设置为“false”来禁用此行为。 The "http.maxConnections" property may be used to control how many idle connections to each server will be held. “http.maxConnections”属性可用于控制每个服务器的空闲连接数。

I don't know what platform you are using, but it could have similar behavior.我不知道您使用的是什么平台,但它可能有类似的行为。

The TME_WAIT state is imposed by TCP, not by Java. TME_WAIT state 是由 TCP 强加的,而不是由 Java 强加的。 It lasts two minutes.持续两分钟。 This is normal.这个是正常的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM