?
Solved

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

Posted on 2006-03-30
24
Medium Priority
?
205 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
      }
      
}           
      
      

0
Comment
Question by:java63
  • 13
  • 11
24 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 16332208
boolean isConnected = false;
Socket socket = null;
 do
      {
...

} while ( counter <= 4 && isConnected == false) ;
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16332232
Of course, in the loop you would have:

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

Author Comment

by:java63
ID: 16332428
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 86

Accepted Solution

by:
CEHJ earned 2000 total points
ID: 16332436
You can put it in the existing one
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16332556
:-)
0
 

Author Comment

by:java63
ID: 16332695
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
 

Author Comment

by:java63
ID: 16332717
This must be somwhere before Menu is called. As menu displays a menu options when you can interact with the server
0
 
LVL 86

Expert Comment

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

You mean the client waits?
0
 

Author Comment

by:java63
ID: 16333053
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 16333164
Well in order to get that sort of thing going, you will have to read at the client, or simulate reading
0
 

Author Comment

by:java63
ID: 16333354
Any suggestion how to go about it? I am willing to give you more points
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 16333413
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
 

Author Comment

by:java63
ID: 16333612
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
 
LVL 86

Expert Comment

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

Author Comment

by:java63
ID: 16333722
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 16333800
>>Instance of what?

Instance of AccountClient.
0
 

Author Comment

by:java63
ID: 16333981
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 16334180
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
 

Author Comment

by:java63
ID: 16334301
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 16334358
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
 

Author Comment

by:java63
ID: 16334392
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 16334417
Do you want to go for the 'further simplification' thing?
0
 

Author Comment

by:java63
ID: 16334550
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 16335280
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

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Suggested Courses
Course of the Month13 days, 10 hours left to enroll

750 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question