My application need to be amended

My application is passing a short message through the socket connection and it should be read back on the client side. I have tested the application and currently only server side is reading the message. I do not know how to change a client so it can read the message too.

I am passing a serialized object from client to a server. on the server side I am using ArrayList to store the object access it and read it out. I think I need to change client accordingly so it can understand that the object to be read is element of the ArrayList. I think the class AccountInfo has to be amended too. Would you please advice.

This is my classes: AccountInfo, AccountClient, AccountServer

import java.io.Serializable;



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


   public AccountInfo(int amount,String message) {
      this.amount = amount;
      this.message = message;
   }
   
   public AccountInfo() {
      // TODO Auto-generated constructor stub
}

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("\n" +TimeStamp + " Transfer no " +message+ " \nTransfering £"+ amount +" from account A to account B \n<<Transferr Done!>>" );
        
   }


}

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

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;

public class AccountClient implements Runnable {

     private 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("192.168.0.4", 4000);
                    haveConnected = socket.isConnected();
                     try {
                         
                       
                          
                          oos = new ObjectOutputStream(socket.getOutputStream());
                        ois = new ObjectInputStream(socket.getInputStream());
                        //socket.setSoTimeout(1000);
                                    
                                    // create serialized object
                        AccountInfo user1 = new AccountInfo();
                       
                        // write the objects to the server
                        oos.writeObject(user1);
                        oos.flush();
                       
                        // read an object from the server
                        user1 = (AccountInfo) ois.readObject();
                        user1.printInfo();
                       
                        oos.close();
                        ois.close();
                    } catch (IOException e) {
                          int x = 1;
                          while(x <5){
                                Thread.sleep(DELAY);
                                System.out.println("Attempt: " + x +
                                      "\t Re-sending Request To the Server");
                                if(x <4){
                                      Thread.sleep(DELAY);
                                      System.err.println("Trying again in " + DELAY + " milliseconds.........");
                                }else
                                      System.err.println("giving up");
                                x++;
                                
                          }
                          continue;
                    }
                    try{
                          Thread.sleep(DELAY);
                    }catch(InterruptedException ex){
                          /*ingore*/
                          continue;
                    }
                    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");

          }
         
     }

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

     }
     
     

            public void createClientLog() {
                  // TODO Auto-generated method stub
                  try {
                        ObjectOutputStream oos = new ObjectOutputStream(new
                                    FileOutputStream("C:\\Logs\\ClientLogs\\Already_Processed.txt"));
                        AccountInfo user1 = new AccountInfo();
                        oos.writeObject(user1);
                oos.flush();
                oos.close();

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

                  
            }
     }


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

import java.io.*;
import java.net.*;
//import java.nio.channels.FileChannel;
import java.util.ArrayList;




public class AccountServer extends Thread {
       private static long DELAY = 2000;
       private ServerSocket dateServer;
      

     /**
      * @param args
      */
     public static void main(String[] args) throws Exception {
           new AccountServer();
     }
     
     public AccountServer() throws Exception {
          
           dateServer = new ServerSocket(4000);
         System.out.println("--------------------------------------------------");
         Thread.sleep(DELAY);
         System.out.println("Server is starting ......... \n");
         Thread.sleep(DELAY);
         System.out.print("Server listening on port 4000...");
         this.start();
     }
     
     public void run() {
          
           while(true) {
                 
                 try{
                      
                       Thread.sleep(DELAY);
                   System.out.println("\nWaiting for new connections ...\n");
                 System.out.println("--------------------------------------------------");
                 Socket client = dateServer.accept();
                 System.out.println("Accepted a connection from: "+
                             client.getInetAddress()+ "");
                 Thread.sleep(DELAY);
                 System.out.print("\nSending acknowledgement....\n");
                 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(150000);
          }catch(Exception e1){
                try{
                      client.close();
                }catch(Exception e){
                      System.out.println(e.getMessage());
                      
                }
                return;
          }
          this.start();
    }
   
    public void run(){
          
          try{
                
                AccountInfo user1 = ( AccountInfo ) ois.readObject () ;
                
                //save request to file called ReceivedLog
                ObjectOutputStream oos = new ObjectOutputStream(new
               FileOutputStream("C:\\Logs\\ReceivedServerLog\\To_Be_Processed.txt"));          
             ArrayList list = new ArrayList();
             list.add(user1);
             oos.writeObject(list);                              
             oos.flush();
             oos.close();
                       
                       
            ObjectInputStream ois = new ObjectInputStream(new
               FileInputStream("C:\\Logs\\ReceivedServerLog\\To_Be_Processed.txt"));
            list = ( ArrayList ) ois.readObject () ;
            ois.close () ;
            AccountInfo info = ( AccountInfo ) list.get ( 0 ) ; // get the  object to be processed
           
                  info.printInfo(); // process it
           
           
            oos = new ObjectOutputStream(new
              FileOutputStream("C:\\Logs\\ProcessedServerLog\\Already_Processed.txt"));
            ArrayList list1 = new ArrayList();
            list1.add ( info ) ; // add the processed request to ProcessedLog
            oos.writeObject ( list1 ) ;
            oos.flush () ;
            oos.close () ;
                       
            oos = new ObjectOutputStream(new
               FileOutputStream("C:\\Logs\\ReceivedServerLog\\To_Be_Processed.txt"));
            list.remove(0);//remove request
            oos.writeObject(list); // overite the receivedLog - minus the processed request
            oos.flush();
            oos.close();
                                                                                         
                       
                       
           
          }
          catch(IOException ex){
                ex.printStackTrace();
          }catch(ClassNotFoundException e){
          }
    }
 }
                
          
 
         


     
   
                           
                       
                     
               
           
             
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:
In the server, unless i've missed it, you only write to files - you don't write to the client, so the client doesn't get to read anything
0
java63Author Commented:
AccountInfo user1 = ( AccountInfo ) ois.readObject () ;

this is the first statement that reads user1 from AccountInfo from within server
Than I create ArrayList instance list and pass user1 object to list
than I write list to (ObjectOutputStream) I think this is the moment when I write to client isn't it?
Do I need to create ArrayList on the client (please look into client? I think client does not understand info handle. What I use on the client was user1.printInfo. I need to pass info to client
Next I am accessing the object on the list
AccountInfo info = ( AccountInfo ) list.get ( 0 ) ;
print it
info.printInfo(); this should happend on the client side

than add info to another file by using write
and overwrite the previous file
0
CEHJCommented:
You need AccountInfo at both ends, yes, but of course you have that already. Just do one of the writes to the client's output stream in addition to saving it to file
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

java63Author Commented:
This the fragment of the code I think I should add writing to client/ please if you know where to put it produce example. I have to go I 'll be back in 3 hours


ObjectInputStream ois = new ObjectInputStream(new
               FileInputStream("C:\\Logs\\ReceivedServerLog\\To_Be_Processed.txt"));
            list = ( ArrayList ) ois.readObject () ;
            ois.close () ;
            AccountInfo info = ( AccountInfo ) list.get ( 0 ) ; // get the  object to be processed
            info.printInfo(); // process it     THIS IS WHEN I PRINT THE OBJECT ON THE SERVER SIDE

           
            oos.writeObject ( info) ;   THIS IS WHAT I ADDED (I think I should pass object info to oos.)
                                                   the problem is that client is reading user.printInfo and does not understand
                                                    info.printInfo
            oos.flush () ;                      still cannot print the message on the client side I gess I need amend client
            oos.close () ;
0
CEHJCommented:
>>oos.writeObject ( info) ;

That's OK as long as oos has been opened on the client's output stream. You would be better off reading and writing List<AccountInfo> throughout, as this will be the most flexible way
0
java63Author Commented:
I added what was required but still client is not displaying anything. Have a look at the client code maybe there is something I cant see

oos = new ObjectOutputStream(socket.getOutputStream());
                        ois = new ObjectInputStream(socket.getInputStream());
                        //socket.setSoTimeout(1000);
                                    
                                    // create serialized object
                        AccountInfo user1 = new AccountInfo();
                        AccountInfo info = new AccountInfo();               THIS IS WHAT I ADDED
                       
                        // write the objects to the server
                        oos.writeObject(user1);
                        oos.flush();
                       
                        // read an object from the server
                        info =  (AccountInfo) ois.readObject();               THIS IS WHAT I ADDED
                        info.printInfo();
                       
                        oos.close();
                        ois.close();
0
CEHJCommented:
You already had the following on the client:

>>
       // create serialized object
                        AccountInfo user1 = new AccountInfo();
                       
                        // write the objects to the server
                        oos.writeObject(user1);
                        oos.flush();
                       
                        // read an object from the server
                        user1 = (AccountInfo) ois.readObject();
                        user1.printInfo();
>>

although as i mentioned above, it would be better to read and write List as this is more flexible. It's the server you need to change to write to the client
0
objectsCommented:
>              ObjectOutputStream oos = new ObjectOutputStream(new
>               FileOutputStream("C:\\Logs\\ReceivedServerLog\\To_Be_Processed.txt"));        

You're overwriting oos (that writes to socket) with a stream that writes to a file
So anything written to it is written to the file instead of back to the client.

Use a different variable name for the stream to write to the file

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
java63Author Commented:
Thanks very much I got the request back in client by creating another try catch block on the server which is seperate of saving request to file. However when I got this right the server displays error when client sends the message. Would you be able to have a look, this is the error that I copied. I think something is wrong with inputstream as the socket is closed, but I can't figure out which one.

--------------------------------------------------
Server is starting .........

Server listening on port 4000...
Waiting for new connections ...

--------------------------------------------------
Accepted a connection from: /192.168.0.2

Sending acknowledgement....
java.net.SocketException: socket closed
      at java.net.SocketInputStream.socketRead0(Native Method)
      at java.net.SocketInputStream.read(Unknown Source)
      at java.net.SocketInputStream.read(Unknown Source)
      at java.io.ObjectInputStream$PeekInputStream.peek(Unknown Source)
      at java.io.ObjectInputStream$BlockDataInputStream.peek(Unknown Source)
      at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
      at java.io.ObjectInputStream.readObject0(Unknown Source)
      at java.io.ObjectInputStream.readObject(Unknown Source)
      at transfer.Connect.run(AccountServer.java:103)

Waiting for new connections ...

--------------------------------------------------
0
objectsCommented:
make sure you aren't closing the socket twice.
0
java63Author Commented:
I want to ask you one more question if you want I can set a new one. Anyway whatever you suggest.
I am going to print some coding which contain method run, within the server part. By the way the error with regard to socket I fixed it, it was basically one unnecessary read method that caused the problem. THe question I want you to ask is this the following code does some logic. Has this logic being implemented in my design looking at the code? After I run this code and check logs, it seems to be fine. So the Received Log does not contain the request being save but Processed Log does. How would I deal with more objects being stored in list?

1. Save request to file called Received Log as To_be_Processed request. It means all request that were not executed yet, because of crash or other things.
2. Write that request to list of ArrayList class and then write that list to Received Log. This means I can have many objects stored within the file.
3. Get the object to be processed and then process it
4. Write that request to another log called Processed Log it means all the request that has being exectued.
5. Overwrite Received Log minus Processed request

THIS IS MY CODE:

public void run(){
          
          try {
           
            AccountInfo user1 = (AccountInfo) ois.readObject();
            int amount = user1.getAmount(100);
            String message = user1.setMessage("1ZA");
           
           
           //String message = null;
                  // ship the object to the client
            AccountInfo user = new AccountInfo(100, message);
            oos.writeObject(user);
            oos.flush();
            // close connections
            //ois.close();
            oos.close();
            client.close();
        }catch(Exception e) {}      
     

          
          try{
                
                
                
                
                AccountInfo user1 = new AccountInfo ();
                
                //save request to file called ReceivedLog
                ObjectOutputStream oos = new ObjectOutputStream(new
               FileOutputStream("C:\\Logs\\ReceivedServerLog\\To_Be_Processed.txt"));          
             ArrayList list = new ArrayList();
             list.add(user1);
             oos.writeObject(list);                              
             oos.flush();
             oos.close();
                       
                       
            ObjectInputStream ois = new ObjectInputStream(new
               FileInputStream("C:\\Logs\\ReceivedServerLog\\To_Be_Processed.txt"));
            list = ( ArrayList ) ois.readObject () ;
            ois.close () ;
            AccountInfo info = ( AccountInfo ) list.get ( 0 ) ; // get the  object to be processed
            //info.printInfo(); // process it
           
           
            oos = new ObjectOutputStream(new
              FileOutputStream("C:\\Logs\\ProcessedServerLog\\Already_Processed.txt"));
            ArrayList list1 = new ArrayList();
            list1.add ( info ) ; // add the processed request to ProcessedLog
            oos.writeObject ( list1 ) ;
            oos.flush () ;
            oos.close () ;
                       
            oos = new ObjectOutputStream(new
               FileOutputStream("C:\\Logs\\ReceivedServerLog\\To_Be_Processed.txt"));
            list.remove(0);//remove request
            oos.writeObject(list); // overite the receivedLog - minus the processed request
            oos.flush();
            oos.close();
                                                                                         
                       
                       
           
          }
          catch(IOException ex){
                ex.printStackTrace();
          }catch(ClassNotFoundException e){
          }
    }
 }
                
          
 
         


     
   
                           
                       
                     
               
           
             

0
objectsCommented:
> I want to ask you one more question if you want I can set a new one. Anyway whatever you suggest.

you'll need to open a new question, I get in trouble o/wise :)
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.