0

I have a simple client - server app that downloads files thru a REST API. As I use basic http auth the files are sent via ssl.

//my download loop
HttpsURLConnection conn;
//some handling of response codes and content-length
InputStream s = conn.getInputStream();
while (true) {
        i = br.read(buffer); //if server shuts down, I stall here
        if (i == -1)
            break;
        downloadedSize += i;
        fis.write(buffer, 0, i);

    }

This all works fine and without issues until the code encounters a situation where the server shuts down a file transfer. At that time the code simply stalls and I have a useless thread.

My question is how to detect that a server has been shut down? In Wireshark I see a RST signal sent, but no exceptions are raised. This seems to me to be a fairly common task and yet I havent found a straightforward answer to it.

Currently Im using a scheduled task, that checks if there was any progres in downloading every now and then. If it detects a problem then it creates a new workerThread and tells my communication service to use that one.

This is a very ugly solution as threads then can end up orphaned.

I tried using available() to peek if there is any data available, but as this is SSL, it always returns 0.

2
  • The two approaches I've seen are to (a) wrap the InputStream in a BufferedStreamReader and use the ready() method, or (b) go up through conn to get the socket and use the getSoTimeout() method. Can't vouch for the effectiveness of either though. Commented Mar 24, 2013 at 14:40
  • ready() wont work, if returns false when using SSL, but I used the timeout solution. Turns out I have been setting the timeout at the wrong time, after actually opening the connection. conn.setReadTimeout(int milis); did the trick. Commented Mar 24, 2013 at 14:57

1 Answer 1

1

Turned out Ive been calling conn.setReadTimeout(5000); at the wrong place

conn = getConnection(address);
    conn.setReadTimeout(5000);
    conn.setRequestMethod("GET");

This will cause the read() to fail correctly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.