Link to home
Start Free TrialLog in
Avatar of java63
java63

asked on

Socket Connection in network failure. I need a code to be amended not theory.Urgent

Hello Experts I believe that something like this is not a challenge for professionals like you. However it is for me. I am giving out 500 points for quick fix of my code.

There is some code in my application that does not work properly. I have 3 classes. What works properly is this:

1.      I send a message and get response back.
2.      When Server is down, client is trying to re-connect for 4 times using loop and finally log off.

3.      When a message is sent from client to server after client is connected lack of acknowledgement will force client to re-connect for a few times. ( I do this by putting server to sleep after client connect to the server, but before acknowledgement is sent back)

This part does not work 100% correct. In case I disable sleep statement on the server, message that is passed from client to the server gets back but strait after that loop still simulates that is trying to reconnect, like in point 3 which is wrong. When I put a brake statement then no. 3 is not looping properly. The second loop in a client code need to be amended.


4.      Message sent to the server is saved in 2 folders Received log and Processed log.


When the server receives this request, serialize it, and save it to above folders. The moment the server receives a request, it writes it to the received log. It then continues to process it, as soon as that's done, the request is then remove from the received log and moved to the processed log.
All I could achieve is that I can save the message to 2 folders and displays back that’s it.


Suggestions: It would be nice to create an input which I could enter from the prompt command. That input could have as it is now integer value amount = 100 plus + string. This input could be stored in a file

This is all my code.


import java.io.Serializable;


public class UserInfo implements Serializable {
      static String TimeStamp;
   /**
       *
       */
       private static final long serialVersionUID = 1L;
       int amount = 0;
      

         public UserInfo(int amount) {
            this.amount = amount;
         }
   
         public void setAmount(int amount){
         this.amount = amount;
   }
   
         public int getAmount() {
            return 0;
      }
   
         public void printInfo() {
         TimeStamp = new java.util.Date().toString();
        
 System.out.println(TimeStamp + " Transfer of £"+amount+" from account A to account B \n<<Transfer Complete!>>" );
   }


}




package account;

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

public class AccountClient {
       Socket socket = null;
       ObjectOutputStream oos = null;
           ObjectInputStream ois = null;
           //SocketAddress socketAdd;
           int amount = 100;
     
public static void main(String argv[]) throws IOException, InterruptedException, ClassNotFoundException {
      
 AccountClient client = new AccountClient();
        client.tryToConnect();
        
   }
            
        
        public void tryToConnect () throws IOException   InterruptedException,ClassNotFoundException {
             boolean reply = true;
             boolean resend = false;
             int i = 0;
             while(true){
                   if(i<4){
                       try{
                         System.out.println("Connecting to the server...............");
                          //open a socket connection
                                 SocketAddress socketAdd = new InetSocketAddress("localhost", 4000);
                        socket = new Socket();
                        if(resend){
                              socket.setSoTimeout(10000);// time out after 10 seconds
                              
                        }
                        socket.connect(socketAdd);
                        if( socket.isConnected()){
                              break;
                        }
                   }catch(UnknownHostException error){
                         i++;
                         resend = true;
                   }catch(IOException ex){
                         i++;
                         resend = true;
                   }
             }else{
                   reply = false;
                   break;
             }// exit from the loop after reconnecting for 4 times
       }//end of loop
       if(reply){
             waitForAnswer();
       }else{
             System.out.println("Server is not available at this time");
             reply = false;
       }
       }

            
               
       

        
       
       
                                                                                   
       public void waitForAnswer() throws IOException, InterruptedException, ClassNotFoundException{
              int i = 0;
              boolean reply = true;
            boolean resend = false;
            while(true){
                 if(i<2){
                       try{
                             //open I/O streams for objects
                             oos = new ObjectOutputStream(socket.getOutputStream());
                           ois = new ObjectInputStream(socket.getInputStream());
                       //}
                        //catch(Exception e){}  
                         
                           //while(true){
                           //if(reply){
                           //if(i<4){
                                 //try{
                           
                                 //socket.setSoTimeout(6000);
                                 System.out.println("<< connection sucesfull >>");
                                 System.out.println(+amount+ " is being sent to account B: " + "....lack of acknowledgement");
                                 socket.setSoTimeout(6000);
                                 break;
                                
                                 }catch(IOException ex1){
                                    
                                   i++;
                                   resend = true;
                                   System.out.println("Attempt: " + i + "\t Re-sending Request To Account B");
                                 }
                           
                                       }else{
                                       reply = false;
                                       System.out.println("Server may be down");
                                       break;
                                       }
                           }
                           
                       }
}
                
---------------------------------------------------------------
                    
 package account;

import java.io.*;
import java.net.*;
import java.nio.channels.FileChannel;



public class AccountServer extends Thread {
      private ServerSocket dateServer;
     

     /**
      * @param args
      */
     public static void main(String[] args) throws Exception {
          // TODO Auto-generated method stub
           new AccountServer();
           
           
               
           //}


     }
     public AccountServer() throws Exception {
          dateServer = new ServerSocket(4000);
          System.out.println("Server listening on port 4000.");
          this.start();
        }

        public void run() {
          while(true) {
            try {
             System.out.println("Waiting for connections.");
             Socket client = dateServer.accept();
             //client.setSoTimeout(10000); // timeout after 10 seconds(not employed yet
             System.out.println("Accepted a connection from: "+ client.getInetAddress());
             Connect c = new Connect(client);
            } catch(Exception e) {}
          }
        }
     }

     class Connect extends Thread {
        private Socket client = null;
        private ObjectInputStream ois = null;
        private ObjectOutputStream oos = null;
         
        public Connect() {}

        public Connect(Socket clientSocket) throws SocketException {
          client = clientSocket;
         
         
          try {
           ois = new ObjectInputStream(client.getInputStream());
           oos = new ObjectOutputStream(client.getOutputStream());
           
//Thread.sleep(15000); // using for testing message lost from client to server
           
           
          } catch(Exception e1) {
              try {
                 client.close();
              }catch(Exception e) {
                   
                  System.out.println(e.getMessage());
              }
              return;
          }
          this.start();
        }

       
        public void run() {
             
             UserInfo user1 = null;
             
             
             
             try {
                 
                    user1 = (UserInfo) ois.readObject();
                    int amount = user1.getAmount();
                   
                   
                  //ship the object to the client
                   UserInfo user = new UserInfo(amount);
                   //user.setAmount(amount);
                   oos.writeObject(user);
                   oos.flush();
                   // close connections
                   ois.close();
                   oos.close();
                   client.close();
                }catch(Exception e) {
                      
                }      
             
        try
           {
              
              
              //save request to file called ReceivedLog  WORK
              ObjectOutputStream oos = new ObjectOutputStream(new
                      FileOutputStream("C:\\Documents and Settings\\Dariusz\\My Documents\\ReceivedLog\\amount.txt"));
            UserInfo user2 = new UserInfo(100);
            oos.writeObject(user2);
            oos.flush();
            oos.close();
           

           
            File file = new File("C:\\Documents and Settings\\Dariusz\\My   Documents\\ReceivedLog\\amount.txt"); // WORK
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
            // Deserialize the object
            UserInfo user11 = (UserInfo) ois.readObject();
            user11.printInfo();
           
         

//Create channel on the source   THIS DOES NOT WORK
            FileChannel srcChannel = new FileInputStream("C:\\Documents and Settings\\Dariusz\\My Documents\\ReceivedLog\\amount.txt").getChannel();
          //Create channel on the destination
            FileChannel dstChannel = new FileOutputStream("C:\\Documents and Settings\\Dariusz\\My Documents\\ProcessedLog\\amount.txt").getChannel();
          //Copy file contents from source to destination
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
          //Close the channels
            srcChannel.close();
            dstChannel.close();
            } catch (IOException e) {
            }


           
           

           
            // retrieve all records from a file        WORK
            //ObjectInputStream ois = new ObjectInputStream(new
                      //FileInputStream("C:\\Documents and Settings\\Dariusz\\My Documents\\ReceivedLog\\amount.txt"));
            //UserInfo user11 = (UserInfo) ois.readObject();
            //invoke a method on the constructed object
            //user11.printInfo();
               
            //save request to file called ProcessedLog
            ObjectOutputStream oos1 = new ObjectOutputStream(new
                      FileOutputStream("C:\\Documents and Settings\\Dariusz\\My Documents\\ProcessedLog\\amount.txt"));
               UserInfo user3 = new UserInfo(100);
               oos1.writeObject(user3);
               oos1.flush();
               ois.close();
               
             //delete file   THIS DOES NOT WORK
               boolean success = (new File("C:\\Documents and Settings\\Dariusz\\My Documents\\ReceivedLog\\amount.txt")).delete();
               if (!success) {
                   // Deletion failed
               }

               
       }
       catch (IOException e)
       {
      e.printStackTrace();
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
      }
      }
       
 }      
   


           


            
Avatar of Mayank S
Mayank S
Flag of India image

First of all, in your AccountServer, you should not create just one thread for listening - you should also create separate threads for each client which connects. I have shown a sample here in this question:

https://www.experts-exchange.com/questions/21757720/Is-there-any-sample-online-for-socket-and-multi-thread.html#16084277
>> socket.setSoTimeout(6000);

Is that necessary? Can you comment out all the setSoTimeout () calls?
>> if( socket.isConnected()){

That is unreliabled. isConnected () will never return the current status of the socket. It will return the status of the last I/O operation (if successful, true, otherwise false). Until you do any I/O on your socket, you cannot be sure if the socket is still connected or not. As long as connect () did not throw any exception, you can try to send/ receive data over it and only then will you come to know if it is *currently* connected or not. If any exceptions are thrown, it means it got disconnected.
>> oos.writeObject(user);

Try doing oos.reset () ; after that.
Ah, sorry :) ignore the first comment. That seems to be correct already.

>> //delete file   THIS DOES NOT WORK
>> boolean success = (new File("C:\\Documents and Settings\\Dariusz\\My Documents\\ReceivedLog\\amount.txt")).delete();

The FileChannel which uses this (in a few lines of code above this one) should be closed in a finally block.
ASKER CERTIFIED SOLUTION
Avatar of Mayank S
Mayank S
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of java63
java63

ASKER

I do appreciate your help, but I need to get first basic functionality before I think about adding threads to clients ect..
I think I should change Client application so it will allow me to provide an input where I can type account id and amount of money to be transfered to a server. The bigest problem in this application is that I am using Serialized Object instead of Print Writer and BufferedReader. What do you think about changing input output type Stream accros the whole application?
 This would allow me to create an input that I could send to  the socket server. I have already done some input code but but don't know how to pass this further to output stream. So the server socket could get it. Maybe you could help me with this, before I think about doing threads with clients. I would be nice to enter those details and then pass them to a socket and then when a while loop is false it could start trying to reconnect 4 times before it logs off. Which I could simulate by putting server to sleep. THIS IS WHAT I NEED NOW. This is a second loop in a client part. I dont know how to pass this futher to the server. This works only in a client part looping for ever.

 public void waitForAnswer() throws IOException, InterruptedException{
             int i = 0;
             boolean reply = true;
           boolean resend = false;
         
           while(true){
                 if(i<2){
                       try{
                            
                            
                           //make an inputBuffer
                             int amount;
                              String input;

                                // inputBuffer
                              BufferedReader inKeyBoard;
                              inKeyBoard = new BufferedReader(new InputStreamReader(System.in));

                                // read tranfer id
                                System.out.print("Insert transfer id: ");
                                input = inKeyBoard.readLine();


                                // read amount
                              System.out.print("What amount you want to transfer: ");
                              amount = Integer.valueOf(inKeyBoard.readLine()).intValue();

                                //write out the input you just wrote
                            
                              
                              TimeStamp = new java.util.Date().toString();
                              out.println(TimeStamp + " Transfer <<no:"+input+ ">> £"+amount+
                                          " from account A to account B \n<<Transfer Completed!>>" );
                            
                             //System.out.println("<< connection sucesfull >>");
                             //System.out.println(+amount+ " is being sent to account B: " + "....lack of acknowledgement");
                             //System.out.println("Attempt: " + i + "\t Re-sending Request To Account B");
                            
                             //open I/O streams for objects
                             out = new PrintWriter(socket.getOutputStream(),true);
                           in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                           
                           if(resend){
                                 TimeStamp = new java.util.Date().toString();
                                  out.println(TimeStamp + " Transfer <<no:"+input+ ">> £"+amount+
                                              " from account A to account B \n<<Transferr Completed!>>" );
                                
                                
                                
                          
                                  
                            }else{
                                  socket.setSoTimeout(10000);//read the response from the Server
                             //user1 = (UserData) ois.readObject();
                             //break;
                            }
                       }
                     catch(IOException ex1){
                       i++;
                       resend = false;
                       
                       
                 }
           }else{
                 boolean reply1 = false;
                 System.out.println("Server may be down");
                     break;
                
           }
           
       
       }
            
         
             
    }
       
     
}

There is one more after changing the SerializedObject stream when I get to the server my actual code complains. IN this is a fragment.
(how to change this code so it could work with PrintWriter,BufferReader)

public void run() {
             
             UserInfo user1 = null;
             
             
             
             try {
                 
                    user1 = (UserInfo) ois.readObject();     I can't use readObject any more please help by amending this
                    int amount = user1.getAmount();
                   
                   
                  //ship the object to the client
                   UserInfo user = new UserInfo(amount);
                   //user.setAmount(amount);
                   oos.writeObject(user);
                   oos.flush();
                   // close connections
                   ois.close();
                   oos.close();
                   client.close();
                }catch(Exception e) {
                      
                }      
>> but I need to get first basic functionality before I think about adding threads to clients ect

That's ok - you don't need more threads at the client.

>>  The bigest problem in this application is that I am using Serialized Object instead of Print Writer and BufferedReader.

Its not a problem - it should be ok. We'll have to figure out where the bugs are.

>> What do you think about changing input output type Stream accros the whole application?

That would take time - plus it depends on what kind of messages you want to exchange. If you want to send String commands, then using PrintWriter and BufferedReader makes sense. If you want to share objects, then you have to serialize them and send them. Another option to look into is RMI, if that is to be done. But all changes will take time.

>> user1 = (UserInfo) ois.readObject();     I can't use readObject any more please help by amending this

Because you removed the definition for ois and its initialization in the constructor?

>> I have already done some input code but but don't know how to pass this further to output stream
>> out = new PrintWriter(socket.getOutputStream(),true);
>> in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

Try putting the in = new BufferedReader () statement before the out = new PrintWriter () statement.

>> out.println(

Then at the other end (server) you will need to use a buffered-reader and read it accordingly. I think you should keep your code as it is for the time being and try making minimum changes. Create a User object using the input which the user has given and then send to the server using ObjectOutputStream. I'm off to home now - will help you with this tomorrow.
Avatar of java63

ASKER

>> user1 = (UserInfo) ois.readObject();     I can't use readObject any more please help by amending this

<<Because you removed the definition for ois and its initialization in the constructor?>>

No I amended this before I send it to you.
PrintWriter out = null;
BufferedReader in = null;

out = new PrintWriter(client.getOutputStream(),true);
                in = new BufferedReader(new InputStreamReader(client.getInputStream()));

The problem is that after change of the above code I cannot run the presented below fragment because I am using readObject which is not applicable to PritWriter and BufferedReader stream. So as far as I concerned I need the some functionality but differnet format.

public void run() {
             
             UserInfo user1 = null;
             
             
             
             try {
                 
                    user1 = (UserInfo) ois.readObject();
                    int amount = user1.getAmount();
                   
                   
                  //ship the object to the client
                   UserInfo user = new UserInfo(amount);
                   //user.setAmount(amount);
                   oos.writeObject(user);
                   oos.flush();
                   // close connections
                   ois.close();
                   oos.close();
                   client.close();
                }catch(Exception e) {
Avatar of java63

ASKER

Does anybody know how to make this loop working. When the server is off, it tries to reconnct 4 times and then logs off.

public class AccountClient {
 

public static void main(String argv[]) throws IOException {
      Socket socket = null;
     
      
      while (true) {
          boolean lackOfConnection = false;
          boolean succesfulConnection = true;
        int counter = 0;
          while(true){
            if(counter  <4){
                  try{
                        // open a socket connection
                        Socket socket1 = new Socket("localhost", 4000);
                        Menu menu = new Menu();
                        menu.run();
                       
                        if(lackOfConnection){
                              try{
                                    Thread.sleep(5000);
                              }catch(InterruptedException ex){
                                    System.out.println("sleep problem");
                              }
                              Socket socket11 = new Socket("localhost", 4000);
                              if(socket11.isConnected()){
                              break;
                              }
                        }catch(IOException e){
                              counter++;
                              lackOfConnection = true;
                              System.out.println("trying to re-connect");
                        }
                  }else{
                        succesfulConnection = false;
                        break;
                  }
            
            }
          
     
          
int counter = 1 ;

do
{
  try
  {
    Socket s = new Socket ( "localhost", 4000 ) ;
    // connected
    break ;
  }
  catch ( Exception e )
  {
  }

  counter ++ ;

} while ( counter <= 4 ) ;

if ( counter > 4 )
  // not connected
else
  // connected
>> The problem is that after change of the above code I cannot run the presented below fragment because I am using
>> readObject which is not applicable to PritWriter and BufferedReader stream.

Then you have to use bufferedReader.readLine () and printWriter.println () for reading/ writing lines. Remove the readObject () and writeObject () instead.
BTW, why a C grade ;-) ? Sorry I was a little occupied with work, hence the delay in replying.
Avatar of java63

ASKER

The functionality of this loop above is connecting to a Server process, through the Menu class which allow to enter an input and interact with the server. I need to show that when the server is down client has to reconnect 4 times and if there is no success logs off. I cannot get it right.
What exactly is the menu class supposed to do - can you post its code if it is not too long? Can you post a new question so that other experts can also help you with it?
Avatar of java63

ASKER

<<The problem is that after change of the above code I cannot run the presented below fragment because I am using readObject which is not applicable to PritWriter and BufferedReader stream.>>
 No, no I am still using Serialized Object. I change slightly my design, so I can insert an input form the console, by invoking Menu class.

WHat I would like to show is when a server is down the connection is re-dial at least 4 times, before client get a message that server is not available.
Another one is when client is connected and send message is lost, so the client could try to reconnect about a few time and then logs off, I can manage this by puting server to sleep for about 10 seconds. So every 10 seconds client will try to reconnect.
So I need help with client loop. Please today.

Menu is not that important now because this is additional fuctionality, that basically add some data to a server and save them to a vector array in a file and print them back. THis is mainly console.

I try to use that the loop you suggested
>> I am still using Serialized Object.

Then you cannot send it through PrintWriter/ read it through BufferedReader.

>> WHat I would like to show is when a server is down the connection is re-dial at least 4 times, before client get a
>> message that server is not available.

That's exactly what my loop will do - keep trying 4 times. Then when it comes out and in the if ( counter > 4 ) statement, you can display a message to the user that the server is not connected.
Avatar of java63

ASKER


<<Then you cannot send it through PrintWriter/ read it through BufferedReader>>

No I told you I have changed everything, so it means I change the streams on server and client respectively.

By the way the loop is ok, so I am happy. There is one more think I need to achieve with this loop.
When you dial connection to the server and get connected, which means you send a data to the server socket. By putting a server to sleep as demonstrated in my server in the below code I am trying not to allow server to send a response for the amount of time I put the server to seep. So the loop need to try to re-connect and show a message that is connected by cannot recieve the output from the server and after a few seconds by putting client to sleep it will demonstrate the same functionality that is doing when the server is off. Do you understand me? If you not let me know. I what to give you some more points.

try {
           ois = new ObjectInputStream(client.getInputStream());
           oos = new ObjectOutputStream(client.getOutputStream());
           Thread.sleep(15000);
>> so it means I change the streams on server and client respectively

Ok. I got confused as I still see ois = new ObjectInputStream and oos = new ObjectOutputStream.

>> By putting a server to sleep as demonstrated in my server in the below code I am trying not to allow server to send a
>> response for the amount of time

Ok.

>> So the loop need to try to re-connect and show a message that is connected by cannot recieve the output

There is no need to re-connect in this case. You can make it wait by bufferedReader.readLine () ; if it is not throwing any exceptions, it means it is connected and waiting for data - you don't need to loop separately.
Avatar of java63

ASKER

I repeat again I am not using Print Writer and BufferedReader but I am using (ois) ObjectInputStream and (oos) ObjectOutputStream.

This is the loop you have suggested with other details. The point of showing that client is reconnecting is that it looks so real when you present screen shots of console. That would like like example below. I want to give you another 500 if you find solution

connectionMsg = "Attempt: " + counter + "\t Trying to Re-connect to Process B";

Attempt: 1 Trying to Re-connect to Process B...........
Attempt: 2 Trying to Re-connect to Process B................
Attempt: 3 Trying to Re-connect to Process B..............
Server is down

This is the loop. How to amend it?. I don't care if I have one extra loop. I attached also Many class

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



public class AccountClient {
 

public static void main(String argv[]) throws IOException {
      Socket socket = null;
      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();
              menu.run();
      }
   }
}
        // connected

--------------------------------------------
 import java.io.IOException;
import java.net.*;
import java.io.*;

public class Menu {
      


//      class handling with the clientside menu
      
      
        boolean running;

        Accounts collection = new Accounts();

        public Menu()
        {
            super();
            running = false;
        }
//      method to get the transfer id.
        static String askTransferId(String prompt) throws IOException, InterruptedException
        {
          String transferId = StringIO.ask(prompt);
          if (transferId.length() == 0) throw new IOException("You must provide a transfer id");
          return transferId;
          
        }
        
//      method to get no of copies
        static int askAmount(String prompt) throws IOException, InterruptedException
        {
          try
          {
            int amount = IntIO.ask(prompt);
            if (amount < 0) throw new InterruptedException("Amount may not be negative");
            return amount;
          }
          catch (NumberFormatException n)
          {
            throw new InterruptedException("Qty must be an integer");
          }
        }

        
        //add account info to Collection accounts which is in server
        void addAccountHandler() throws IOException, InterruptedException
        {
         try{

               AccountInfo accountInfo = new AccountInfo(0, null);
               accountInfo.ask("\nEnter account details...");
              if (collection.find(accountInfo.getTransferId()) != null)
              System.out.println("ERROR: Item transfer id already exists\n");
              else
               collection.add(accountInfo);
               FileOutputStream fos = new FileOutputStream("C:\\Documents and Settings\\Dariusz\\My Documents\\ReceivedLog\\accounts.out");
               ObjectOutputStream oos = new ObjectOutputStream(fos);
               oos.writeObject(collection);
               oos.flush();
               oos.close();
               fos.close();

              } catch(Exception e) {
              System.out.println(e.getMessage());
              }
        }
        
        // add qty to stock
        void receiveHandler() throws IOException, InterruptedException
        {
          String transferId = askTransferId("transferId: ");
          try{
          FileInputStream fis = new FileInputStream("C:\\Documents and Settings\\Dariusz\\My Documents\\ReceivedLog\\accounts.out");
          ObjectInputStream ois = new ObjectInputStream(fis);
          Accounts collection = (Accounts) ois.readObject();
          AccountInfo accountInfo =  (AccountInfo) collection.find(transferId);
          if (accountInfo == null)
          {
            System.out.println("ERROR: cannot find " + transferId);
            return;
          }

          


          //FileOutputStream fos = new FileOutputStream("accounts.out");
         // ObjectOutputStream oos = new ObjectOutputStream(fos);
          //oos.writeObject(collection);
          //oos.flush();
          //oos.close();
          //fos.close();
          }catch (Exception e) {
            System.out.println(e.getMessage());
          }
        }


        
        
//      print all the accounts
        void printHandler()
         {
             try {

                 FileInputStream fis = new FileInputStream("accounts.out");
                 ObjectInputStream ois = new ObjectInputStream(fis);
                 Accounts collection = (Accounts) ois.readObject();
                 collection.print("The accounts are...");

             } catch (Exception e) {
                 System.out.println(e.getMessage());
             }
         }
                
        void quitHandler() throws IOException{
              running = false;
        }
        
        public void run() throws IOException
        {
          running = true;
          char option;

          System.out.println("\nThe Bager Bank\n");

          while ( running )
          {
            try
            {
              option = StringIO.readMenuOption("\nA)dd P)rint R)eceive Q)uit");
              switch ( option )
              {

                case 'A':  addAccountHandler();
                           break;


                case 'P':  printHandler();
                           break;

                
                          
                //case 'R':  receiveHandler();
              //break;

                case 'Q':  quitHandler();
              break;

                case '\0': break;  // do nothing

                default:
                      System.out.println("ERROR: Invalid option");
                break;
              }
            }
            catch (InterruptedException i)
            {
                  System.out.println("ERROR: " + i.getMessage() + '\n');
            }
          } // END WHILE when option == 'Q'
        }

}
     

     
>> I repeat again I am not using Print Writer and BufferedReader but I am using (ois) ObjectInputStream and (oos)

Damn, I was confused.

int counter = 1 ;      
Socket s = null ;
do
{
  try
  {
    System.out.println ( "Attempt: " + counter + " trying to connect to server. " ) ;
    s = new Socket ( "localhost", 4000 ) ;
    // connected
    break ;
  }
  catch ( Exception e )
  {
  }
  counter ++ ;
} while ( counter <= 4 ) ;
if ( counter > 4 ){
  System.out.println("Server cannot be located");
}
else // connected
{
  Menu menu = new Menu();
  menu.run();
}
Avatar of java63

ASKER

Mayan I've got that working, when you send it first time. What I what is this:

What I would like to show is that when client is connected, and no acknowledgement is received client will wait (it would be nice to display that client is looping about 4 times asking for acknowledgement) and when the time expires it even get connected or exit the connection. The difference between the presented loop and required functionality is that here client is reconnecting when the server is completely off, in the other one I would like to show that client is connected but message from the server is not coming back. It would look something like this in terms of messages sent.

WHAT TO ADD: (I'll give you another 500 points)
You can put it in another thread - make your class implement Runnable:

// this is your main thread
dataReceived = false ; // make this a data-member of your class
Thread t = new Thread ( this ) ;
t.start () ;
String data = bufferedReader.readLine () ; // wait for data to come
dataReceived = true ;

....

public void run ()
{
  int count = 0 ;

  while ( true )
  {
    if ( dataReceived == false )
      System.out.println ( "Waiting for data to come " + count ) ; // end if
    else
      break ;
    try
    {
      Thread.sleep ( 1000 ) ;
    }
    catch ( Exception e )
    {
    }
  }
}
Avatar of java63

ASKER

Hello mayankeagle, the above loop is not working. I do not know what is really the problem. Maybe the way I arrange to code code causes to trouble. First of all I don't think I can use this(Look at below code); as I am doing Object Serialized. Anyway I'll print it for you how I did it. If I want to give you another 500 points what to do. Do I need to set a new question? But then everyone will start answering.

<<String data = bufferedReader.readLine () ; // wait for data to come>>

Obviously this code is not working accept for the first loop that you suggested. As I promis I put 500 points when this will work. Do you need any other code

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

public class AccountClient implements Runnable{
        boolean dataReceived = false;
        Socket socket = null;
        
         public static void main(String argv[]) throws IOException, ClassNotFoundException {
             int counter = 1 ;       
             boolean dataReceived = true;
             Thread t = new Thread ( this ) ;  
             t.start ()
     
        
        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();
              menu.run();
              
             //connected
      }
       }
    public void run() {
      
      int count = 0 ;
        while(true)
        {
             
            if ( dataReceived == false )
                  System.out.println ( "Waiting for data to come " + count ) ; // end if
                else
                  break ;
            try{
                  Thread.sleep(10000);
            }
            catch(Exception e){
                  System.out.println("server is not available");
                  
            }
                  
            

        }
       }
       }
      


>>  If I want to give you another 500 points what to do. Do I need to set a new question?

If you want to open a new question, it is your wish. You cannot give more than 500 points for another question. And if it is a new question, all experts have the right to post on it :) and if they can help you, they do deserve the points. Sometimes even I get busy with work. Its a free forum and everybody has equal rights :)

I will see the code and let you know my thoughts.
Ok, what is the output that comes right now? And what is it that you expect to see (how different from the current output)?
Avatar of java63

ASKER

What I would like 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.
>> This also depends on the socket.setSoTimeout(10000); on the client side.

Can you eliminate that line?

>> in the other one client is connected but message from the server is not coming back and it throws exceptions on the
>> client side

Then put a catch block and in the catch block, log a message with a counter saying that its waiting for acknowledgement.
Avatar of java63

ASKER

How about this? All together

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
      }
       }
}
            
            
Yes, looks ok.

>> isConnected = s.isConnected();

Make that isConnected = true ; because isConnected () at this stage will anyway always return true.
Avatar of java63

ASKER

Hello Manyan I said :

>> server client is connected but message from the server is not coming back and it throws exceptions on the
>> client side

then you said;

Then put a catch block and in the catch block, log a message with a counter saying that its waiting for acknowledgement.


Tried everything I do not work. Can you show me were to insert that catch statement so I could get that functionality. I am just completely stack with this
Not required - I have posted it in the other question that you have asked regarding that problem. Check the code there.
Avatar of java63

ASKER

I do not mind to give best mark possible but people do not come back with their responses early enough
Sometimes we get busy with our own work :) that is why. I am still working on the other Q which you had posted - will get back as soon as I have time for it.
Avatar of java63

ASKER

I do have the preassure too, therefore pushing you guys
>> I do have the preassure too, therefore pushing you guys

Yes but we work for free here :) hence sometimes we have to prioritize our own first.
Avatar of java63

ASKER

I do not know if you work for free or not, but there true is I pay for this service to get solution, maybe not that much but still pay.

I say again the reason for low mark is that solution your providing me with are not workable, this is first.
second their not on time I have beeing asking your for one loop almost 1.5 week non of them send by you worked. I ask you because I think of myself as a beginner but you guys are sitting there and recognized as experts. At least this is what I thought. sorry to be a bit to hard but don't tell me what mark I should give it to you. I can give you best possible mark, with most pleasure if you give me something that can work quickly and efficiently.
We cannot post full working code for something because its difficult to spend so much of time writing an entire application for somebody, and also because its against site rules. So we work mostly in the mode of consultation and let the questioner also try to figure out how it has to be done, to some extent.

As for the loop that you asked for in your other question - we could not get it working fully because you had not posted your server code for long, but hopefully I will find time to look into it. Till then - keep that question open, don't close it.
Avatar of java63

ASKER

I DID SEND THE WHOLE WORKABLE CODE TO YOU SERVER + CLIENT + BASE CLASS AND CEHJ Said he will run it and let me know, but that was 4 days ago
Avatar of java63

ASKER

This is again my whole working code that I posted 4 days ago as an open question

Hello Experts I am presenting to you runnable code. Simple and clear design. You can run it and see what is doing it. It sends serialized objects within the single message containing string plus integer, and gets saved in the file on the server side.


What I need from you is to help me to add to my design one more loop. I have already got one which tries to re-connect the connection 4 times and logs off when server is not available.

Another loop supposed to connect to the server by running the server and throw an exception when acknowledgement is not coming back. This is achieved by putting  Output Stream on the server to sleep by using Thread.sleep(10000); which provoke client to throw exception and  display message like this

System.out.println("Attempt: " + counter + "\t Re-sending Request To Process B");

This is my code which contain classes UserInfo, AccountClient and AccountServer

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 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();
        user1.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
      }


   }
}


---------------------------------------------------

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



public class AccountServer extends Thread {
      private ServerSocket dateServer;

     /**
      * @param args
      */
     public static void main(String[] args) throws Exception {
          // TODO Auto-generated method stub
           new AccountServer();
           
           
               
           //}


     }
     public AccountServer() throws Exception {
          dateServer = new ServerSocket(4000);
          //dateServer.setSoTimeout(100000); // timeout after 10 seconds(not employed yet
          System.out.println("Server listening on port 4000.");
          this.start();
        }

        public void run() {
          while(true) {
            try {
             System.out.println("Waiting for connections.");
             Socket client = dateServer.accept();
             System.out.println("Accepted a connection from: "+
     client.getInetAddress());
             Connect c = new Connect(client);
            } catch(Exception e) {}
          }
        }
     }

     class Connect extends Thread {
        private Socket client = null;
        private ObjectInputStream ois = null;
        private ObjectOutputStream oos = null;
         
        public Connect() {}

        public Connect(Socket clientSocket) {
          client = clientSocket;
          try {
           ois = new ObjectInputStream(client.getInputStream());
           oos = new ObjectOutputStream(client.getOutputStream());
           //Thread.sleep(10000);
          } catch(Exception e1) {
              try {
                 client.close();
              }catch(Exception e) {
                System.out.println(e.getMessage());
              }
              return;
          }
          this.start();
        }

       
        public void run() {
             
             UserInfo user1 = null;
             
             
             
             try {
                  //Thread.sleep(20000);
                    user1 = (UserInfo) ois.readObject();
                    int amount = user1.getAmount();
                   
                   
                   // ship the object to the client
                   UserInfo user = new UserInfo(amount, null);
                   user.setAmount(amount);
                   oos.writeObject(user);
                   oos.flush();
                   // close connections
                   ois.close();
                   oos.close();
                   client.close();
                }catch(Exception e) {}      
             //}
        try
           {
                // save request to file called ReceivedLog
                ObjectOutputStream oos = new ObjectOutputStream(new
                          FileOutputStream("C:\\Documents and Settings\\Dariusz\\My Documents\\ReceivedLog\\amount1.out"));
                UserInfo user2 = new UserInfo(100, null);
                oos.writeObject(user2);
                oos.flush();
                oos.close();
               
                // retrieve all records from a file
                ObjectInputStream ois = new ObjectInputStream(new
                          FileInputStream("C:\\Documents and Settings\\Dariusz\\My Documents\\ReceivedLog\\amount1.out"));
                UserInfo user11 = (UserInfo) ois.readObject();
                //invoke a method on the constructed object
                   user11.printInfo();
                   ois.close();
                   
           }
           catch (IOException e)
           {
          e.printStackTrace();
           } catch (ClassNotFoundException e) {
               e.printStackTrace();
          }
          }
           
     }


--------------------------------------------------------------
   
import java.io.Serializable;



public class UserInfo implements Serializable {
     static String TimeStamp;
     private int amount = 100;
     private String message = "";
   /**
      *
      */
     private static final long serialVersionUID = 1L;


   public UserInfo(int name,String message) {
      this.amount = name;
   }
   
   public void setAmount(int amount){
        this.amount = amount;
   }
   
   public int getAmount() {
          return 0;
     }
   public void setMessage(String message){
        this.message = message;
   }
   public String getMessage(){
        return message;
   }
   
   

   public void printInfo() {
        TimeStamp = new java.util.Date().toString();
        System.out.println(TimeStamp + " Transfer no" + " 1ZA" + " \nTransfering £"+ amount +" from account A to account B \n<<Transferr Done!>>" );
   }


}
>> I DID SEND THE WHOLE WORKABLE CODE TO YOU SERVER + CLIENT + BASE CLASS

Stop talking in capitals, it looks like shouting. We're here to help, not to listen to shouts because like I said, we don't get paid for all the time that we spend with you here and on your questions. Yes, I know that you posted your code 4 days back but before that we did not have all of it so we could not run all of it.

>> AND CEHJ Said he will run it and let me know

Well, if he did not reply, then ask him :) not me.

I am trying to work on a code for your other question and I will post it there on that one so that CEHJ also gets to see it. Let's not make this question any longer - it is already taking a lot of time to load and is a very long page.