简体   繁体   中英

Connection to server times out android

I am trying to check if server is online in android. I have following code on a button onclick listener block:

                boolean exists = false;

            try {
                SocketAddress sockaddr = new InetSocketAddress("google.com", 80);
                // Create an unbound socket
                Socket sock = new Socket();

                // This method will block no more than timeoutMs.
                // If the timeout occurs, SocketTimeoutException is thrown.
                int timeoutMs = 2000;   // 2 seconds
                sock.connect(sockaddr, timeoutMs);
                exists = true;
            }catch(Exception e){
            }
            if ( exists == true) {
                Toast.makeText(getApplicationContext(), "Host is reachable!!! =)",
                        Toast.LENGTH_LONG).show();
            }
            else {
                Toast.makeText(getApplicationContext(), "Host is NOT reachable!!! =(",
                        Toast.LENGTH_LONG).show();
            }

Thing is that, whatever host or ip i check, its always offline.

What could be the problem?

I have this permission in androidmanifest:

    <uses-permission android:name = "android.permission.INTERNET"/>
<uses-permission  android:name="android.permission.ACCESS_NETWORK_STATE"/>

Try this

InetAddress.getByName(host).isReachable(timeOut)

or

boolean exists = false;

try {
    SocketAddress sockaddr = new InetSocketAddress(ip, port);
    // Create an unbound socket
    Socket sock = new Socket();

    // This method will block no more than timeoutMs.
    // If the timeout occurs, SocketTimeoutException is thrown.
    int timeoutMs = 2000;   // 2 seconds
    sock.connect(sockaddr, timeoutMs);
    exists = true;
}catch(Exception e){
}

I prefer to use HttpClient. Something like:

getURL = "http://www.msftncsi.com/ncsi.txt"


HttpGet getHttp   = new HttpGet(getURL);
HttpParams httpParameters = new BasicHttpParams();

int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

int timeoutSocket     = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

HttpClient client = new DefaultHttpClient(httpParameters); 

HttpResponse responseGet = client.execute(getHttp);  
HttpEntity resEntityGet = responseGet.getEntity(); 

If HttpEntity returns null then I assume there is no connectivity.

You must surround with try catch and assume there is no connectivity when enter in the catch

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