简体   繁体   中英

Android check if remote server is online

I am new to Android programming and I have been facing problems that didn't exist in native Java. When I run this code in my computer, it runs correctly. But, when I run it in my device.I get nothing, I even tried to post the message to UI and there's no logcat for this. I am not sure what is wrong.

                try{
                    Socket socket = new Socket(serverAddr, SERVER_PORT);
                    Log.i("TAG","Socket connected");    
                }catch(IOException e){
                    Log.i("TAG","Socket not connected");
                }

Update 1: I just changed the code..nothing much and realized that after 2 minutes or so it does what it was supposed to do?? Is is anything to do with keep alive flags? Or is there anyway that I can run the code just for a second or two and stop it. Please understand that the code below the socket creation line executes only after 2 minutes if the server is dead. Here below is my code:

    try{
InetAddress serverAddr = InetAddress.getByName(serverIP);   
//Line below executes with no delay
postToUI("Trying to connect to standalone server" + "\n\n");
socket = new Socket(serverAddr, SERVER_PORT);
//Line below executes after 2 minutes
postToUI("Successfully connected to standalone server" + "\n\n");

}catch(ConnectException e){
    postToUI("Socket not connected");
}catch(IOException e){
    postToUI("Socket not connected");
}   

I have done very few Andrioid development so don't bite me smiley .

Possible reasons why the host might not communicate with the client

  • Host has firewall which might be closing the connection (unlikely)
  • Host might have unexpectly shutdown eg power failure (unlikely)
  • Host might not properly port forwared (possibly)
  • Your andriod app doesn't have the proper manifest that allows the use of sockets.
  • Your andrioid device you are testing on might have its internet disabled which can enabled easily.
  • Host's address could have changed if it is dynamic.

For logcat, I think that logcat only displays log messages for the main thread. But I am unsure.

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