I need to simulate that client is connected but cannot obtain an acknowledgement

I need to simulate that client is connected but cannot obtain an acknowledgement, so client will throw an exception stating that acknowledgement cannot be receive at this time. At the moment this code is looping four times when server is off. but it does not provide simulation when client is connected but could not receive acknowledgement. This is so far what i have done. Any suggestion?

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

public class AccountClient {
         public static void main(String argv[]) {
            ObjectOutputStream oos = null;
            ObjectInputStream ois = null;
            int counter = 1;
            boolean isConnected = false;

            do{
            try {
              // open a socket connection
              Socket socket = new Socket("localhost", 4000);
              isConnected  = socket.isConnected();
            
              
              // open I/O streams for objects
              oos = new ObjectOutputStream(socket.getOutputStream());
              ois = new ObjectInputStream(socket.getInputStream());
              
              // create serialized object
              UserInfo user2 = new UserInfo(100, "");
              UserInfo user3 = new UserInfo(100,"");
              UserInfo user4 = new UserInfo(100,"");
              
              // write the objects to the server
              oos.writeObject(user2);
              oos.writeObject(user3);
              oos.writeObject(user4);
              oos.flush();
              
              // read an object from the server
              user2 = (UserInfo) ois.readObject();
              user3 = (UserInfo)ois.readObject();
              user4 = (UserInfo)ois.readObject();
              user2.printInfo();
              user3.printInfo();
              user4.printInfo();
              
            
              oos.close();
              ois.close();
            } catch(Exception e) {
              System.out.println(e.getMessage());
            }
            
            counter++;
            }while ( isConnected == false && counter <= 4  );
            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{
                      
                      
                 }
                   //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:
Are we going around in circles java63? ;-)

Did you actually try what i mentioned before (to *not* send anything to the client and set the read timeout on the client)?
0
java63Author Commented:
I am so sorry this is mistake I copied the message that was already posted instead of something else and then hit the enter button, I could not stop to appear as a posted question. My loop works fine. The question I wanted actually asks refer to the same loop

System.err.printf("Cannot connect. Trying again in %d milliseconds\n", DELAY);
What library do you need to import in order to be readable

I had to do it differently but that not the same? and I do not too many lines
System.out.print("Cannot connect. Trying again in %d milliseconds\n" );
System.err.println(DELAY);



0
CEHJCommented:
>>What library do you need to import in order to be readable

You need Java >= 1.5

If you haven't got it, do

System.err.println("Cannot connect. Trying again in " + DELAY + " milliseconds");
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
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

java63Author Commented:
CEHJ as I said the loop suggested by you works fine, but there is still little tiny thing I would like to achieve in terms of dealing with lack of acknowledgement.

In this loop I use 2 try and 2 related catch statements. 1 try takes place when I bind to socket to the server port, end if something goes wrong with binding it throws a second catch when client is trying to reconnect 4 times and finally when counter > 4 it displays the message that client "Failed to connect. Giving up".

The 2 try is dealing with reading data from input and output stream. If I put hold on it by stopping any input output back from the server and set a timeout on the reading, as you suggested the 2 try will throw 1 exception with the message "Failed to read server acknowledgement. Trying again". At the moment is displays this message once and stops.

The second message is my question, how to incorporate another loop that would allow that message to loop like in the first instance (trying to reconnect 4 times), so after the counter > 4 times it would stop. As you can see, logicaly it would make sense for this message to loop as it says ...Failed to read server.....trying again...

This is the code:

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class AccountClient implements Runnable {

     private final static long DELAY = 2000; // 2 second delay between retries
     private static ObjectInputStream ois;
     private static ObjectOutputStream oos;
     private boolean haveReadServerAcknowledgement;
     private boolean haveConnected;
     private boolean haveConnectedSatisfactorily;
      

     public static void main(String argv[]) throws IOException,
               ClassNotFoundException {
          System.setProperty("sun.net.client.defaultReadTimeout", "5000"); // Five second acknowledgement window
         
          AccountClient client = new AccountClient();
          new Thread(client).start();
     }

     void connectClient() throws IOException {
          int counter = 1;

          do {
               try {
                    
                    Socket socket = new Socket("localhost", 4000);
                    haveConnected = socket.isConnected();
                     try {
                           oos = new ObjectOutputStream(socket.getOutputStream());
                           ois = new ObjectInputStream(socket.getInputStream());
                           socket.setSoTimeout(10000);
                          
                           // create serialized object
                           UserInfo user1 = new UserInfo(100, null);
                       
                                // write the objects to the server
                               oos.writeObject(user1);
                               oos.flush();
                       
                                // read an object from the server
                               user1 = (UserInfo) ois.readObject();
                               oos.close();
                              ois.close();
                   
                     } catch (IOException e) {
                         System.err.println("Failed to read server acknowledgement. Trying again");
                         continue;                  //HERE WOULD BE NICE TO LOOP
                    }
                    haveReadServerAcknowledgement = true;
                    haveConnectedSatisfactorily = (haveReadServerAcknowledgement && haveConnected);
               } catch (Exception e) {
                    System.out.println(e.getMessage());
                    System.err.println("Cannot connect. Trying again in " + DELAY + " milliseconds");

                   
                    try {
                         Thread.sleep(DELAY);
                    } catch (InterruptedException ex) {
                         /* ignore */
                    }
               }
               counter++;
          } while (haveConnectedSatisfactorily == false && counter <= 4);

          if (counter > 4) {
               System.err.println("Failed to connect. Giving up");

          }
          // not connected
          else {}// connected
          }
     

     public void run() {
          try {
               connectClient();
          } catch (IOException e) {
               e.printStackTrace();
          }

     }
}


0
CEHJCommented:
// read an object from the server
user1 = (UserInfo) ois.readObject();
haveReadServerAcknowledgement = true; //<< this needs to go in


Making the above correction will not solve the problem. Can you tell me (by including the appropriate debug statements) what line is reached before it gives up?)
0
java63Author Commented:
This is the last line that is riched before it stops. Assuming that I bock the reading from the server put the reading in client to timeout.

} catch (IOException e) {
                         System.err.println("Failed to read server acknowledgement. Trying again");
                         continue;  

Otherwise is goes fine
0
java63Author Commented:
This is the last line before is hungs up


oos = new ObjectOutputStream(socket.getOutputStream());
                           ois = new ObjectInputStream(socket.getInputStream());
                           System.out.println("hello");
                           socket.setSoTimeout(500);

                                 .................
                                 ......................
0
CEHJCommented:
OK. What you're going to have to do in that case is to *create the Thread and call run on it repeatedly* (if necessary)

I'd recommend that instead of

>>
new Thread(client).start();
>>

you have

client.start();

and do the handling of 0 > n <= 4 calls of new Thread(this).start() *in the client itself*
0
java63Author Commented:
My I ask for an example?  I think in this case I need to create method public void start(). What about a Runnable Interace do I still keep that?

public class AccountClient implements Runnable {

or it should be that

public class AccountClient extends Thread {   if I go for that then I need to call the

ublic void run() {
          try {
               //connectClient();
                Thread(this).start();
          } catch (IOException e) {
               e.printStackTrace();
          }

     }
0
java63Author Commented:
Is this gonna be something like this appart I do not know how to go about this loop

I have eliminated the method run where I was calling connectClient and create method run for all loops

public static void main(String argv[]) throws IOException,
               ClassNotFoundException {
          System.setProperty("sun.net.client.defaultReadTimeout", "5000"); // Five second acknowledgement window
         
          AccountClient client = new AccountClient();
          //new Thread(client).start();
          new Thread(this).start();       HERE IS COMPLAINING ABOUT THIS
          client.start();
         

     }

     public void run(){
                 
                 //void connectClient() throws IOException {
          int counter = 1;

          do {
               try {
                          ...............................
0
CEHJCommented:
>>I think in this case I need to create method public void start(). What about a Runnable Interace do I still keep that?

Yes and yes

>>or it should be that

Yes
0
CEHJCommented:
>>  new Thread(this).start();       HERE IS COMPLAINING ABOUT THIS

Remove it. Threads should be handled *in* start
0
java63Author Commented:
Sorry not sure what you mean?
0
CEHJCommented:
AccountClient client = new AccountClient();
client.start();

is the only code you should have in main
0
java63Author Commented:
I have done that

public static void main(String argv[]) throws IOException,
               ClassNotFoundException {
          System.setProperty("sun.net.client.defaultReadTimeout", "5000"); // Five second acknowledgement window
         
          AccountClient client = new AccountClient();
          //new Thread(client).start();
          client.start();
     }

     private void start() {
           new Thread(this).start();
           int counter = 0;
          
           haveReadServerAcknowledgement = true;
         haveConnectedSatisfactorily = (haveReadServerAcknowledgement && haveConnected);
            counter++;
     while (haveConnectedSatisfactorily == false && counter <= 4);
     if (counter > 4) {
         System.err.println("Failed to connect. Giving up");

    }
            
            
      }

      void connectClient() throws IOException {
          int counter = 1;

          do {
               try {
                        ..............................

So I understand when I rich first catch as a result of blocked reading I should call start method to invoke a loop. would you look at what I have got in start method is this make sens?
0
CEHJCommented:
No, you need to create threads *inside* the loop if necessary
0
java63Author Commented:
So where should be mehtod start() then. sorry I am having problem with this.
0
CEHJCommented:
That's in the right place. I have to go out. Read carefully what i've said and you should get there
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.