Link to home
Start Free TrialLog in
Avatar of java63
java63

asked on

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


     
   
                           
                       
                     
               
           
             
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

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
Avatar of java63
java63

ASKER

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
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
Avatar of java63

ASKER

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 () ;
>>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
Avatar of java63

ASKER

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();
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
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia 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

ASKER

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

--------------------------------------------------
make sure you aren't closing the socket twice.
Avatar of java63

ASKER

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


     
   
                           
                       
                     
               
           
             

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