Android:如何检查服务器是否可用?

时间:2020-12-04 16:55:14

I am developing an application which connects to the server. By now the login and data transmission works fine if theserver is available. The problem arises when the server is unavailable. In this case the method sends a login request and waits for the response.

我正在开发一个连接到服务器的应用程序。到目前为止,如果服务器可用,登录和数据传输工作正常。服务器不可用时会出现问题。在这种情况下,该方法发送登录请求并等待响应。

Does anyone know how to check if the server is available (visible)?

有谁知道如何检查服务器是否可用(可见)?

The pseudocode of the simple logic that has to be implemented is the following:

必须实现的简单逻辑的伪代码如下:

  1. String serverAddress = (Read value from configuration file) //already done
  2. String serverAddress =(从配置文件中读取值)//已经完成
  3. boolean serverAvailable = (Check if the server serverAddress is available)//has to be implemented
  4. boolean serverAvailable =(检查服务器serverAddress是否可用)//必须实现
  5. (Here comes the logic which depends on serverAvailable)
  6. (这是依赖于serverAvailable的逻辑)

7 个解决方案

#1


45  

He probably needs Java code since he's working on Android. The Java equivalent -- which I believe works on Android -- should be:

他可能需要Java代码,因为他在Android上工作。 Java相当 - 我相信在Android上运行 - 应该是:

InetAddress.getByName(host).isReachable(timeOut)

#2


17  

With a simple ping-like test, this worked for me :

通过简单的类似ping的测试,这对我有用:

static public boolean isURLReachable(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
        try {
            URL url = new URL("http://192.168.1.13");   // Change to "http://google.com" for www  test.
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setConnectTimeout(10 * 1000);          // 10 s.
            urlc.connect();
            if (urlc.getResponseCode() == 200) {        // 200 = "OK" code (http connection is fine).
                Log.wtf("Connection", "Success !");
                return true;
            } else {
                return false;
            }
        } catch (MalformedURLException e1) {
            return false;
        } catch (IOException e) {
            return false;
        }
    }
    return false;
}

Do not forget to run this function in a thread (not in the main thread).

不要忘记在线程中运行此函数(不在主线程中)。

#3


5  

you can use

您可以使用

InetAddress.getByName(host).isReachable(timeOut)

but it doesn't work fine when host is not answering on tcp 7. You can check if the host is available on that port what you need with help of this function:

但是当主机没有在tcp 7上应答时,它无法正常工作。您可以通过此功能检查主机在该端口上是否可用您需要的内容:

public static boolean isHostReachable(String serverAddress, int serverTCPport, int timeoutMS){
    boolean connected = false;
    Socket socket;
    try {
        socket = new Socket();
        SocketAddress socketAddress = new InetSocketAddress(serverAddress, serverTCPport);
        socket.connect(socketAddress, timeoutMS);
        if (socket.isConnected()) {
            connected = true;
            socket.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        socket = null;
    }
    return connected;
}

#4


3  

public static boolean IsReachable(Context context) {
    // First, check we have any sort of connectivity
    final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
    boolean isReachable = false;

    if (netInfo != null && netInfo.isConnected()) {
        // Some sort of connection is open, check if server is reachable
        try {
            URL url = new URL("http://www.google.com");
            //URL url = new URL("http://10.0.2.2");
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setRequestProperty("User-Agent", "Android Application");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(10 * 1000);
            urlc.connect();
            isReachable = (urlc.getResponseCode() == 200);
        } catch (IOException e) {
            //Log.e(TAG, e.getMessage());
        }
    }

    return isReachable;
}

try it, work for me and dont forget actived android.permission.ACCESS_NETWORK_STATE

尝试一下,为我工作,不要忘记actived android.permission.ACCESS_NETWORK_STATE

#5


2  

Are you working with HTTP? You could then set a timeout on your HTTP connection, as such:

你在使用HTTP吗?然后,您可以在HTTP连接上设置超时,如下所示:

private void setupHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, CONNECTION_TIMEOUT);
    //...

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(
            httpParams, schemeRegistry);
    this.httpClient = new DefaultHttpClient(cm, httpParams);
}

If you then execute a request, you will get an exception after the given timeout.

如果您随后执行请求,则在给定的超时后将收到异常。

#6


2  

public boolean isConnectedToServer(String url, int timeout) {
try{
    URL myUrl = new URL(url);
    URLConnection connection = myUrl.openConnection();
    connection.setConnectTimeout(timeout);
    connection.connect();
    return true;
} catch (Exception e) {
    // Handle your exceptions
    return false;
 }
}

#7


0  

Oh, no no, the code in Java doesn't work: InetAddress.getByName("fr.yahoo.com").isReachable(200) although in the LogCat I saw its IP address (the same with 20000 ms of time out).

哦,不,不,Java中的代码不起作用:InetAddress.getByName(“fr.yahoo.com”)。isReachable(200)虽然在LogCat中我看到了它的IP地址(20000毫秒的超时时间相同) 。

It seems that the use of the 'ping' command is convenient, for example:

似乎使用'ping'命令很方便,例如:

Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("ping fr.yahoo.com -c 1"); // other servers, for example
proc.waitFor();
int exit = proc.exitValue();
if (exit == 0) { // normal exit
    /* get output content of executing the ping command and parse it
     * to decide if the server is reachable
     */
} else { // abnormal exit, so decide that the server is not reachable
    ...
}

#1


45  

He probably needs Java code since he's working on Android. The Java equivalent -- which I believe works on Android -- should be:

他可能需要Java代码,因为他在Android上工作。 Java相当 - 我相信在Android上运行 - 应该是:

InetAddress.getByName(host).isReachable(timeOut)

#2


17  

With a simple ping-like test, this worked for me :

通过简单的类似ping的测试,这对我有用:

static public boolean isURLReachable(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
        try {
            URL url = new URL("http://192.168.1.13");   // Change to "http://google.com" for www  test.
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setConnectTimeout(10 * 1000);          // 10 s.
            urlc.connect();
            if (urlc.getResponseCode() == 200) {        // 200 = "OK" code (http connection is fine).
                Log.wtf("Connection", "Success !");
                return true;
            } else {
                return false;
            }
        } catch (MalformedURLException e1) {
            return false;
        } catch (IOException e) {
            return false;
        }
    }
    return false;
}

Do not forget to run this function in a thread (not in the main thread).

不要忘记在线程中运行此函数(不在主线程中)。

#3


5  

you can use

您可以使用

InetAddress.getByName(host).isReachable(timeOut)

but it doesn't work fine when host is not answering on tcp 7. You can check if the host is available on that port what you need with help of this function:

但是当主机没有在tcp 7上应答时,它无法正常工作。您可以通过此功能检查主机在该端口上是否可用您需要的内容:

public static boolean isHostReachable(String serverAddress, int serverTCPport, int timeoutMS){
    boolean connected = false;
    Socket socket;
    try {
        socket = new Socket();
        SocketAddress socketAddress = new InetSocketAddress(serverAddress, serverTCPport);
        socket.connect(socketAddress, timeoutMS);
        if (socket.isConnected()) {
            connected = true;
            socket.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        socket = null;
    }
    return connected;
}

#4


3  

public static boolean IsReachable(Context context) {
    // First, check we have any sort of connectivity
    final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
    boolean isReachable = false;

    if (netInfo != null && netInfo.isConnected()) {
        // Some sort of connection is open, check if server is reachable
        try {
            URL url = new URL("http://www.google.com");
            //URL url = new URL("http://10.0.2.2");
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setRequestProperty("User-Agent", "Android Application");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(10 * 1000);
            urlc.connect();
            isReachable = (urlc.getResponseCode() == 200);
        } catch (IOException e) {
            //Log.e(TAG, e.getMessage());
        }
    }

    return isReachable;
}

try it, work for me and dont forget actived android.permission.ACCESS_NETWORK_STATE

尝试一下,为我工作,不要忘记actived android.permission.ACCESS_NETWORK_STATE

#5


2  

Are you working with HTTP? You could then set a timeout on your HTTP connection, as such:

你在使用HTTP吗?然后,您可以在HTTP连接上设置超时,如下所示:

private void setupHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, CONNECTION_TIMEOUT);
    //...

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(
            httpParams, schemeRegistry);
    this.httpClient = new DefaultHttpClient(cm, httpParams);
}

If you then execute a request, you will get an exception after the given timeout.

如果您随后执行请求,则在给定的超时后将收到异常。

#6


2  

public boolean isConnectedToServer(String url, int timeout) {
try{
    URL myUrl = new URL(url);
    URLConnection connection = myUrl.openConnection();
    connection.setConnectTimeout(timeout);
    connection.connect();
    return true;
} catch (Exception e) {
    // Handle your exceptions
    return false;
 }
}

#7


0  

Oh, no no, the code in Java doesn't work: InetAddress.getByName("fr.yahoo.com").isReachable(200) although in the LogCat I saw its IP address (the same with 20000 ms of time out).

哦,不,不,Java中的代码不起作用:InetAddress.getByName(“fr.yahoo.com”)。isReachable(200)虽然在LogCat中我看到了它的IP地址(20000毫秒的超时时间相同) 。

It seems that the use of the 'ping' command is convenient, for example:

似乎使用'ping'命令很方便,例如:

Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("ping fr.yahoo.com -c 1"); // other servers, for example
proc.waitFor();
int exit = proc.exitValue();
if (exit == 0) { // normal exit
    /* get output content of executing the ping command and parse it
     * to decide if the server is reachable
     */
} else { // abnormal exit, so decide that the server is not reachable
    ...
}