We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

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

java63
java63 asked
on
Medium Priority
223 Views
Last Modified: 2010-03-31
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
      }
      
}           
      
      

Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2016

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

} while ( counter <= 4 && isConnected == false) ;
CERTIFIED EXPERT
Top Expert 2016

Commented:
Of course, in the loop you would have:

s = new Socket ( "localhost", 4000 ) ;
isConnected = s.isConnected();

Author

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?
CERTIFIED EXPERT
Top Expert 2016
Commented:
You can put it in the existing one

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
CERTIFIED EXPERT
Top Expert 2016

Commented:
:-)

Author

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
      }
       }
}
            
                  

Author

Commented:
This must be somwhere before Menu is called. As menu displays a menu options when you can interact with the server
CERTIFIED EXPERT
Top Expert 2016

Commented:
>>when client is connected it waits for a time set by Thread.sleep on the server

You mean the client waits?

Author

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
      }
       }
}
            
                  
CERTIFIED EXPERT
Top Expert 2016

Commented:
Well in order to get that sort of thing going, you will have to read at the client, or simulate reading

Author

Commented:
Any suggestion how to go about it? I am willing to give you more points
CERTIFIED EXPERT
Top Expert 2016

Commented:
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

Author

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
      }
       }
}
            
                  
CERTIFIED EXPERT
Top Expert 2016

Commented:
The first thing you need to do is to create an instance. Only crude test code should run much in the main method

Author

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
CERTIFIED EXPERT
Top Expert 2016

Commented:
>>Instance of what?

Instance of AccountClient.

Author

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;
             
CERTIFIED EXPERT
Top Expert 2016

Commented:
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

Author

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
CERTIFIED EXPERT
Top Expert 2016

Commented:
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

Author

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?
CERTIFIED EXPERT
Top Expert 2016

Commented:
Do you want to go for the 'further simplification' thing?

Author

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
      }
       }
        
CERTIFIED EXPERT
Top Expert 2016

Commented:
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
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.