繁体   English   中英

强制断开连接时,BufferedReader.readLine()挂起

[英]BufferedReader.readLine() hangs when connection forcefully disconnected

我不断从Web服务获取数据。

URLConnection connection;
    BufferedReader in = null;

    try {
        SharedPreferences preferences = context.getSharedPreferences(
                "MyPreferences", Context.MODE_PRIVATE);
        int timeoutConnection = Integer.parseInt(preferences.getString(
                "timeout", "60")) * 1000;
        URL urlAddress = new URL(preferences.getString("apiUrl",
                defaultURL));
        connection = urlAddress.openConnection();
        connection.setConnectTimeout(timeoutConnection);
        in = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        final String[] inputLine = { null };
        int i=0;
        while (isOnline() && (inputLine[0] = in.readLine()) != null) {   // isOnline checks if connected to internet.
            ((Activity) context).runOnUiThread(new Runnable() {
                    public void run() {
                        callback.run(inputLine[0]);
                    }
                });
        }
    } catch (Exception e) {
        ..
        ..
    }  

直到我连接到互联网,这才能正常工作。 但是,一旦我强行断开连接, inputLine[0] = in.readLine()就不会响应。 我没有例外。
那么如何检查两者之间的连接是否断开? 仅使用readLine()或其他方式。
注意 :我很少看到建议使用BufferedReader.ready()解决方案。 我也尝试过,但总是返回false。
请为我提供一个可行的解决方案。
谢谢

设置连接的读取超时 如果只是丢弃数据包,TCP可能需要很长时间才能检测到断开的连接。

    connection = urlAddress.openConnection();
    connection.setReadTimeout(10000); // 10 seconds
    connection.setConnectTimeout(timeoutConnection);

我认为您需要使用.read(char[] cbuf, int off, int len)而不是.readLine() ,然后进行自己的行处理。 这是该BufferedReader.read方法的文档:

此方法实现Reader类的相应read方法的常规协定。 作为一个额外的便利,它尝试通过重复调用基础流的读取方法来读取尽可能多的字符。 重复执行此迭代读取,直到满足以下条件之一:

  • 已读取指定数量的字符,
  • 基础流的read方法返回-1,表示文件结束,或者
  • 基础流的ready方法返回false,指示其他输入请求将被阻止。

如果对基础流的第一次读取返回-1表示文件结束,则此方法返回-1。 否则,此方法返回实际读取的字符数。

(强调我的。)

看起来保证不会阻止read ,因为它询问基础流是否有任何东西可提供。

不过请记住,它可能不会返回您要求的字符数,甚至可能返回0。

但是,您仍然有一个问题,那就是如果它返回0,那么您不知道是由于连接断开还是Web服务器尚未产生任何东西。

暂无
暂无

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

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