【问题标题】:Read Data From Http Response rarely throws BindException: Address already in use从 Http 响应读取数据很少抛出 BindException: Address already in use
【发布时间】:2011-05-11 10:49:39
【问题描述】:

我使用以下代码从 http 请求中读取数据。 在一般情况下它工作得很好,但有时“httpURLConnection.getResponseCode()”会抛出 java.net.BindException: Address already in use: connect

     ............
     URL url = new URL( strUrl );
     httpURLConnection = (HttpURLConnection)url.openConnection();
     int responseCode = httpURLConnection.getResponseCode();
     char charData[] = new char[HTTP_READ_BLOCK_SIZE];
     isrData = new InputStreamReader( httpURLConnection.getInputStream(), strCharset );
     int iSize = isrData.read( charData, 0, HTTP_READ_BLOCK_SIZE );
     while( iSize > 0 ){
            sbData.append( charData, 0, iSize );
            iSize = isrData.read( charData, 0, HTTP_READ_BLOCK_SIZE );
     }
     .................





 finally{
            try{
                if( null != isrData ){
                    isrData.close();
                    isrData = null;
                }

                if( null != httpURLConnection ){
                    httpURLConnection.disconnect();
                    httpURLConnection = null;
                }

                strData = sbData.toString();
             }
            catch( Exception e2 ){
            }

在 Java 1.6、Tomcat 6 上运行的代码。 谢谢

【问题讨论】:

    标签: java http tomcat6


    【解决方案1】:

    摆脱 disconnect() 并关闭阅读器。您的本地端口用完了,使用 disconnect() 会禁用 HTTP 连接池,这是解决该问题的方法。

    【讨论】:

    • 好点,不幸的是它没有帮助,我仍然以相同的频率在日志文件中播种异常。
    • 那你需要睡觉了。您的出站端口即将用完,即在 TIME_WAIT 期间内全部使用完毕。
    【解决方案2】:

    你需要close()Reader在完全读取流之后。这将释放底层资源(套接字等)以供将来重用。否则系统将耗尽资源。

    适用于您的案例的基本 Java IO 习惯用法如下:

    Reader reader = null;
    try {
        reader = new InputStreamReader(connection.getInputStream(), charset);
        // ...
    } finally {
        if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
    }
    

    另见:

    【讨论】:

    • 一切都关闭了。这个问题通过添加 Thread.sleep(500) 解决了,但是我不喜欢这个解决方案。
    • 是否您已经关闭了资源?如果您没有这样做并且您实际上已修复代码以执行此操作,那么您需要重新启动机器以强制释放未关闭的资源。
    猜你喜欢
    • 2022-12-26
    • 2022-12-28
    • 2022-10-23
    • 2020-12-17
    • 2013-08-03
    • 1970-01-01
    • 2023-02-07
    • 2013-02-05
    • 2021-01-18
    相关资源
    最近更新 更多