简体   繁体   中英

What can I do to resolve the connection issue?

I have an app that uses JSoup to connect to a web server, and it works fine. Unfortunately, the said web server isn't very reliable. I get SocketException because of time-out connection quite often. I make the connection in a modified IntentService, and I just simply repeat onHandleIntent(intent) in the catch(Exception e) block.

catch(Exception e){
Log.d(Tag, "in catch Exception block...");   
onHandleIntent(intent);
}

Theoretically, this should work. But sometimes, I get stack over flow error, and the app ended quite ungracefully. So, what can I do to make it better?

I want to continue to call onHandleIntent, so, maybe I have to call it in iteration instead of recursively. If you can give me advice on how to implement this iteratively, it would be very helpful. Thanks!

I want to continue to call onHandleIntent, so, maybe I have to call it in iteration instead of recursively.

That is correct. If you handle this recursively, a server that continually times out will inevitably result in a stack overflow.

If you can give me advice on how to implement this iteratively, it would be very helpful. Thanks!

Something like this:

for (int tries = 1; ; tries++) {
    Connection conn = null;
    try {
        // attempt to connect
        // do stuff
    } catch (SocketException ex) {
        if (/* timed out */ && tries < MAX_TRIES) {
            continue;
        }
        // report exception
    } finally {
        if (conn != null) {
            // close it
        }
    }
    break;
}

(Maybe someone can think of a less "clunky" way to write this ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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