This is socket connection application. I working on simulating a newtork failure.

What I would like to do is to show is that when client is connected, and no acknowledgement is received client will wait for the amount of time the output on the server is put to sleep. When the time of the Thread.sleep on the server side expires it even get back connected or exit the connection. This also depends on the socket.setSoTimeout(10000); on the client side.
The presented below loop in a client code loops 4 times when the connection to the server socket is not available. The difference between one I want to have is that here client is reconnecting when the server is completely off, in the other one client is connected but message from the server is not coming back and it throws exceptions on the client side. I could imagine this by having similar display on the console.

System.out.println ("Attempt: " + counter + "\t Trying to Re-connect to Process B"

Attempt: 1 Waiting for acknowledgement from Process B...........
Attempt: 2  Waiting for acknowledgement from Process B................
Attempt: 3  Waiting for acknowledgement from Process B..............
Server is down



it would be nice to display that client is looping about 4 times asking for acknowledgement only for the matter of making screen shots more clear in console as the effect of testing.
This is the code that works, and includes the loop that dial the connection when the server is down, before client connects.

package account;

import java.io.*;
import java.net.*;




public class AccountClient implements Runnable{
        
        Socket socket = null;
        public static void main(String argv[]) throws IOException, ClassNotFoundException {
             int counter = 1 ;       
                                      
     
        do
      {
        try
        {
          Socket s = new Socket ( "localhost", 4000 ) ;
         
          // connected
          break ;
        }
        catch ( Exception e ){
              System.out.println(e.getMessage());
        }
       
       
        counter ++ ;
       
     
      } while ( counter <= 4 ) ;

      if ( counter > 4 ){
            System.out.println("Server cannot be located");
      }
        // not connected
      else{
            Menu menu = new Menu();  THIS CLASS PROVIDES  INPUT AND INTERACT WITH OTHERS(SERVER)
              menu.run();
              
             //connected
      }
      
}           
      
      

java63Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CEHJCommented:
boolean isConnected = false;
Socket socket = null;
 do
      {
...

} while ( counter <= 4 && isConnected == false) ;
0
CEHJCommented:
Of course, in the loop you would have:

s = new Socket ( "localhost", 4000 ) ;
isConnected = s.isConnected();
0
java63Author Commented:
Just to clarify. Do you mean I should insert this code to existing loop or create another one. And if create another one, which you give any suggestion how. Should I create Runnable Interface and put another looop in seperate thread?
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

CEHJCommented:
You can put it in the existing one
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
CEHJCommented:
:-)
0
java63Author Commented:
I added all the suggested code but still not sure how to test, that when client is connected it waits for a time set by Thread.sleep on the server and then throws exception saying that there is a lack of acknowledgement until sleep stops and reconnects again.

This is a server side code
try {
           ois = new ObjectInputStream(client.getInputStream());
           oos = new ObjectOutputStream(client.getOutputStream());
           Thread.sleep(20000);

This is a client amended code as you suggested


import java.io.*;
import java.net.*;




public class AccountClient {
      //boolean isConnected = false;
      Socket socket = null;
        
        
      


      //private BufferedReader bufferedReader;
       public static void main(String argv[]) throws IOException, ClassNotFoundException {
             int counter = 1 ;
             boolean isConnected = false;
             
     
        
        do
      {
        try
        {
          Socket s = new Socket ( "localhost", 4000 ) ;
          isConnected = s.isConnected();
         
          // connected
          break ;
        }
        catch ( Exception e ){
              System.out.println(e.getMessage());
        }
       
       
        counter ++ ;
       
     
      } while ( counter <= 4 && isConnected == false ) ;

      if ( counter > 4 ){
            System.out.println("Server cannot be located");
      }
        // not connected
      else{
            Menu menu = new Menu();
              menu.run();
              
             //connected
      }
       }
}
            
                  
0
java63Author Commented:
This must be somwhere before Menu is called. As menu displays a menu options when you can interact with the server
0
CEHJCommented:
>>when client is connected it waits for a time set by Thread.sleep on the server

You mean the client waits?
0
java63Author Commented:
I mean client is connected succesfully, but the output from the server is not comming back(so client waits), because below the output I put a server to sleep. this simulates that the message request was lost. So then client throws different exception that acknowledgement has not being received

 oos = new ObjectOutputStream(client.getOutputStream());
           Thread.sleep(20000);

I tried to do something like this, but I dont think it works

public class AccountClient {
      //boolean isConnected = false;
      Socket socket = null;
        
        
      


      //private BufferedReader bufferedReader;
       public static void main(String argv[]) throws IOException, ClassNotFoundException {
             int counter = 1 ;
             boolean isConnected = false;
             
     
        
        do
      {
        try
        {
          Socket s = new Socket ( "localhost", 4000 ) ;
          isConnected = s.isConnected();
         
          // connected
          break ;
        }
        catch ( Exception e ){
              System.out.println(e.getMessage());
        }
       
       
        counter ++ ;
       
     
      } while ( counter <= 4 && isConnected == false ) ;

      if ( counter > 4 ){
            System.out.println("Server cannot be located");
      }
        // not connected
      else{
            if(isConnected){
                  System.out.println("Waiting for server response" + counter++);
            }
            
      
     
            
            else{
     
            Menu menu = new Menu();
              menu.run();
            }
              
             //connected
      }
       }
}
            
                  
0
CEHJCommented:
Well in order to get that sort of thing going, you will have to read at the client, or simulate reading
0
java63Author Commented:
Any suggestion how to go about it? I am willing to give you more points
0
CEHJCommented:
Create a 'haveReadSomethingFromServer' boolean instance variable.

private volatile boolean haveReadSomethingFromServer;

Create a java.util.Timer and check for that variable still being false after n seconds

What would set it to true is if you *do* read something from the client
0
java63Author Commented:
Can you look at my loop and say if everythink is OK before I add anything. To be honest I am not sure if I understand third line of you intruction. can you put some coding or refer to some examples. Thanks


import java.io.*;
import java.net.*;
import java.util.Timer;




public class AccountClient {
      //boolean isConnected = false;
      Socket socket = null;
      private volatile boolean haveReadSomethingFromServer;

        
        
      


      //private BufferedReader bufferedReader;
       public static void main(String argv[]) throws IOException, ClassNotFoundException {
             int counter = 1 ;
             boolean isConnected = false;
             
     
        
        do
      {
        try
        {
          Socket s = new Socket ( "localhost", 4000 ) ;
          isConnected = s.isConnected();
         
          // connected
          //break ;
        }
        catch ( Exception e ){
              System.out.println(e.getMessage());
        }
       
       
        counter ++ ;
       
     
      } while ( counter <= 4 && isConnected == false ) ;

      if ( counter > 4 ){
            System.out.println("Server cannot be located");
      }
        // not connected
      else{
            if(isConnected == false){
                  System.out.println("Waiting for server response" + counter++);
            }else{
     
            Menu menu = new Menu();
              menu.run();
            }
              
             //connected
      }
       }
}
            
                  
0
CEHJCommented:
The first thing you need to do is to create an instance. Only crude test code should run much in the main method
0
java63Author Commented:
Can you please give me more clue about what you really mean or if you not sure what you mean maybe I'll set a new question.

Instance of what? Honestly I need fast solution, as I am already late
0
CEHJCommented:
>>Instance of what?

Instance of AccountClient.
0
java63Author Commented:
OK I have done it. What would you suggest nex?

public class AccountClient {
      
      Socket socket = null;
      AccountClient client = null;
      
      private volatile boolean haveReadSomethingFromServer;
      
        
        
      


      //private BufferedReader bufferedReader;
       public static void main(String argv[]) throws IOException, ClassNotFoundException {
             AccountClient client = new AccountClient();
             int counter = 1 ;
             boolean isConnected = false;
             
0
CEHJCommented:
A simpler implementation would be

public static void main(String argv[])  {
           System.setProperty("sun.net.client.defaultReadTimeout", "5000"); // Only allow 5 seconds of wait before read
           AccountClient client = new AccountClient();
           client.connect();
}

In the connect method, set up and try to read from the Socket. An exception will be thrown after 5 seconds if nothing is read
0
java63Author Commented:
So you suggesting to create client method that would hold the whole loop, or outside the loop. How this System. setProperty method will be understand by client method
0
CEHJCommented:
Yes you could hold the whole loop. The read setting operates at the protocol reading level and will be understood by the client. The attempting to read business is distinct from attempting to connect n times. If you want to simplify still further you can set the sun.net.client.defaultConnectTimeout too, but that won't try to reconnect
0
java63Author Commented:
Would you please print some more code so I can see what you really mean. Is this method gonna be Surrounding the existing loop or how do you see this?
0
CEHJCommented:
Do you want to go for the 'further simplification' thing?
0
java63Author Commented:
No I think I like the one before. this is what I have done so far, if you willing to add something it would be great

public class AccountClient {
      
      Socket socket = null;
      AccountClient client = null;

      public static void main(String argv[]) throws IOException, ClassNotFoundException {
             AccountClient client = new AccountClient();
            
                                  client.connectClient()    THIS LINE IS SHOWING A MISTAKE DO NOT WAY
             
             
              void connectClient ()  {
               
                                   int counter = 1 ;
               boolean isConnected = false;
        
            do
      {
        try
        {
          Socket s = new Socket ( "localhost", 4000 ) ;
          isConnected = s.isConnected();
         
          // connected
          //break ;
        }
        catch ( Exception e ){
              System.out.println(e.getMessage());
        }
       
       
        counter ++ ;
       
     
      } while ( counter <= 4 && isConnected == false ) ;

      if ( counter > 4 ){
            System.out.println("Server cannot be located");
      }
        // not connected
      else{
            
     
            Menu menu = new Menu();
              menu.run();
            }
              
             //connected
      }
       }
        
0
CEHJCommented:
I had to go out. Posted something in the new one that works for me. We could add something vis-a-vis attempting to read there too
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.