我不断从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。
请为我提供一个可行的解决方案。
谢谢

最佳答案

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

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

07-24 09:47
查看更多