简体   繁体   中英

java.net.Socket don't throw IOException at Android

  • What I DO :

    Write an upload program using java.net.Socket at Android Mobile

  • What I WANT:

    Connect the Server, When IOException happens(such as the bad network state,no network etc.),try to connect the server three times

  • What The Question:

    Close the WIFI or Mobile GPRS and just run it, No IOexception happened and APP just stop at this point long long time.

  • Just See My Code:

     try { do { socket = new Socket(); SocketAddress socketAddress = new InetSocketAddress(API.UPLOAD_SERVER, API.UPLOAD_PORT); socket.setPerformancePreferences(1, 0,0); socket.setSoTimeout(1000); socket.connect(socketAddress, 2000); attempt = 3; } while (attempt < 3); mListener.onStart(); } catch (SocketException e) { Log.e("UploadTask","exception"); return; } catch (UnknownHostException e) { return; } catch (IOException ioe) { try { Thread.sleep(100); } catch (InterruptedException e) { return ; } attempt++; if (attempt == 3) { return; } } 
  • Help Me or ...: I hope someone can help me,I will wait your answer online, Thanks.

you have nothing output or exception if you close WIFI or GPRS. Does this mean you app will run over or you code will stay in one sentence,for example, the "connect" method?

I have a suggestion. If you want to explore the API of android, that's OK. OR

Maybe you can test Connectivity before your socket connect.

private boolean isOpenNetwork() {  
    ConnectivityManager connManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
    if(connManager.getActiveNetworkInfo() != null) {  
        return connManager.getActiveNetworkInfo().isAvailable();  
    }  

    return false;  
}

hope this can help..

PS: I have no idea about the direct solution to your question, for I have no idea about the socket realize detail. Maybe someone else can explain it.

Assuming that the "connect" method succeeds (which can happen), the API is build in a way that you get IOException(s) when actually reading/writing to the streams of the socket.

socket = new Socket();
SocketAddress socketAddress = new InetSocketAddress(API.UPLOAD_SERVER, API.UPLOAD_PORT);
socket.setPerformancePreferences(1, 0,0);
socket.setSoTimeout(1000);
socket.connect(socketAddress, 2000);

InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();

// Now for example, if you want to read some data
int data;
try( data = is.read() ){
   // Usual processing
} catch( IOException ){
   // Disconnected... try reconnecting etc.
}

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