Ragaisis
Ragaisis

Reputation: 2750

How to catch connection lost error on open socket connection?

I have service that runs new Thread. Thread is responsible for open connection with server

serverAddr = InetAddress.getByName(serverIP);
socket = new Socket(serverAddr, port);

Then I run listenToServer() method that has loop and always reads from the server.

scanner = new Scanner(socket.getInputStream());
message = scanner.nextLine();
while (!message.equals(null)
    message = scanner.nextLine();
//...
 }

Based on the message I call some methods that send instruction to the activity that handles many situations and thread is still listening for new instructions from the server.

But when Internet connection is lost (turned off wi-fi or server shut down) app will crash. How could I handle this error and safely stop & unbind service and stop working thread (that was launched from the service).

Upvotes: 0

Views: 2475

Answers (3)

Jyothish
Jyothish

Reputation: 587

Add timeout to the socket connection.

mSocket.setSoTimeout(10000);

if there isn't any response, for 10 seconds it will throw SocketTimeoutException and in the catch of this exception close the connection if exists, then connect again.

catch (SocketTimeoutException e){
                if(mSocket.isConnected()){
                    disconnect();
                }
                connect();
            }

Upvotes: 2

user207421
user207421

Reputation: 310936

But when Internet connection is lost (turned off wi-fi or server shut down) app will crash.

No it won't. It will get an IOException.

How could I handle this error and safely stop & unbind service and stop working thread (that was launched from the service).

That's what the IOException is for.

Your question doesn't really make sense.

Upvotes: 1

Prachi
Prachi

Reputation: 3672

         public static boolean isNetworkAvailable(Context context           ,DialogInterface.OnDismissListener dismissListener, Boolean endActivity){

     ConnectivityManager conMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);  
     NetworkInfo info= conMgr.getActiveNetworkInfo();

     boolean isNetworkAvailable=false;
       if(info != null && info.isConnected()) { 
          isNetworkAvailable=true;
       //    Log.e("NetworkInfo","Connected State");  
       }  
       else{  
         isNetworkAvailable=false;
         alertNetworkConnection(context,dismissListener,endActivity);
     //  Log.e("NetworkInfo","Not Connected state");  
       }

     return isNetworkAvailable;
}

Upvotes: 0

Related Questions