连接服务器超时android

时间:2015-02-18 13:43:29

标签: java android sockets

我正在尝试检查服务器是否在android中处于联机状态。 我在按钮onclick监听器块上有以下代码:

                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();
            }

事情是,无论我检查的主机或IP,它总是脱机。

可能是什么问题?

我在androidmanifest中有这个权限:

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

2 个答案:

答案 0 :(得分:0)

试试这个

InetAddress.getByName(host).isReachable(timeOut)

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){
}

答案 1 :(得分:0)

我更喜欢使用HttpClient。类似的东西:

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(); 

如果HttpEntity返回null,那么我假设没有连接。

你必须使用try catch包围并假设在输入catch

时没有连接