【问题标题】:Timeout an InputStreamInputStream 超时
【发布时间】:2012-10-16 12:14:53
【问题描述】:

有没有办法为 InputStream 设置超时?

我当前的代码如下所示:

public class DownloadFile implements Runnable {
private EventHandler eh;
private String source;
private String destination;

public void run(){
    try {
        Log.d("Download", "Download... " + source);
        URL url = new URL(source);

        URLConnection connection = url.openConnection();
        connection.connect();

        int fileLength = connection.getContentLength();

        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream(destination + "t");

【问题讨论】:

    标签: java android sockets


    【解决方案1】:

    我认为对于您的要求,您可以使用

    HttpURLConnection.setReadTimeout()
    

    这些链接可能会对您有所帮助。

    1. Is it possible to read from a Java InputStream with a timeout?
    2. Class HttpURLConnection
    3. Can I set a timeout for a InputStream's read() function?

    【讨论】:

    • 1.此外,如果连接未在所需时间内发生,还可以使用 connectionTimeout() 关闭套接字 2.想要处理“慢速服务器”的情况吗?即每'x'秒后发送小块数据的服务器。这样的服务器每次都会重置 readTimeout,因此整个“读取”操作需要很长时间。要处理这种情况,请使用两个线程,第一个线程将处理您的“读取”操作。第二个线程将休眠 'y' 秒。当它唤醒并且第一个线程仍在运行时,它会杀死第一个线程。
    【解决方案2】:

    您可以启动一个 AsyncTask 或仅启动一个单独的线程并将其休眠超时时间,然后检查事务是否已准备好。或者更好的是,您可以向 Handler 发布延迟消息,然后检查您的任务是否准备就绪。您也可以使用计时器,但我认为 Handler 解决方案是最优雅的。

    看看这个:http://developer.android.com/reference/android/os/Handler.html

    【讨论】:

    • 我的问题是它在下载时中断并且永远不会结束。
    猜你喜欢
    • 2020-04-06
    • 1970-01-01
    • 2010-10-22
    • 2015-10-16
    • 2016-01-02
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多