MAIN MENU           BIODATA              ASSIGNMENTS                 TUTORIALS                EMAILS

 

DISTRIBUTED SYSTEMS(TCT 2034)

ASSIGNMENT 2

(SOCKET PROGRAMMING)

QUESTION:

Modify the earlier program to allow the client to modify the contents of the file and send the file back to server for storage. The user can edit the file in a JTextArea, then click a save changes button to send the file back to server.

 

Answer:

//Server.java

import java.net.*;

import java.io.*;

 

public class Server {

 

    private ServerSocket server;

    private Socket connection;

    private BufferedReader input;

    private BufferedWriter output;

 

    //constructor

    public Server()

    {

 

    //create ServerSocket

    try {

       server = new ServerSocket(5000, 10);

    }

 

    //process problems communicating with server

    catch(IOException exception) {

       exception.printStackTrace();

       System.exit(0);

    }

  }

 

 

 

  //run server

  public void runServer()

  {

 

    //wait for connection, get streams, read file

    try {

 

       //allow server to accept connection

       connection = server.accept();

 

       //set up output stream

       output = new BufferedWriter(new OutputStreamWriter(

          connection.getOutputStream()));

 

       //flush output buffer to send header information

          output.flush();

 

       // set up input stream

       input = new BufferedReader(new InputStreamReader(

          connection.getInputStream()));

 

       //receive file name from client

       File file = new File(input.readLine());

 

       String result;

 

       //send file to client

       if(file.exists()) {

           BufferedReader fileInput = new BufferedReader(

              new InputStreamReader(new FileInputStream(file)));

 

       //write first 13 characters

       output.write("The file is:\n", 0, 13);

       output.flush();

 

       //read first line of file

       result = fileInput.readLine();

 

       while(result != null) {

           output.write(result + '\n', 0, result.length() + 1);

           output.flush();

           result = fileInput.readLine();

       }

     }

 

     //file does not exist

     else {

         result = file.getName()+"does not exist\n";

         output.write(result,0,result.length());

         output.flush();

     }

 

     //close streams and socket

     output.close();

     input.close();

     connection.close();

    }

 

    //process problems communicating with server

    catch(IOException ioException){

       System.err.println("IOException has occured!");

       ioException.printStackTrace();

 

       System.exit(0);

  }

 }  // end method run server

 

 

 //execute application

 public static void main(String args[])

 {

   Server application=new Server();

 

   application.runServer();

 }

 

}//end class Server

 

 

 

/**Write student information to the file**/

private synchronized static void writeToFile(Student student){

            try{

                        //Append it to "student.dat"

                        raf.seek(raf.length());

                        student.writeSti=udent(raf);

 

                        //Dispaly data saved

                        jtaLog.append("The following info saved in the file\n");

                        jtaLog.append(student.toString());

     }

     catch(Exception ex){

                         jtaLog.append(new Date() + ": " + ex);

     }

}

 

 

//Define a thread to process the client registration

class RegistrationThread extends Thread{

            //The socket to serve a client

            private Socket socket;

 

            //Buffered reader to get input from the client

            private BufferedReader in;

 

}

 

public void run(){

            String name;

            String street;

            String city;

 

            try{

                        //Receive data from the client

                        name=new String(in.readLine());

                        street=new String(in.readLine());

                        city=new String(in.readLine());

 

 

                        //create student instance

                        Student student=

                                                new Student(name, street, city);

 

                        writeToFile(student);

     }

     catch(IOException ex){

                         System.out.println(ex);

     }

 

}

 

 

 

//Client.java

import java.awt.*;

import java.net.*;

import java.io.*;

import java.awt.event.*;

 

//Java extrension packeges

import javax.swing.*;

 

public class Clientedit extends JFrame implements ActionListener{

   private JTextField fileField;

   private JTextArea contents;

   private JButton jbtSave = new JButton("Save Changes");

   private BufferedReader bufferInput;

   private BufferedWriter bufferOutput;

   private Socket connection;

   private JPanel panel;

   private JLabel label;

   private JScrollPane scroller;

 

   //set up GUI, connect to server, get streams

   public Clientedit()

   {

 

      //set up GUI

      label=new JLabel("Enter file name to retrieve:");

 

      panel=new JPanel();

      panel.setLayout(new GridLayout(1,2,0,0));

      panel.add(label);

 

              fileField=new JTextField();

              fileField.addActionListener(this);

              panel.add(fileField);

 

              contents=new JTextArea();

              scroller=new JScrollPane(contents);

 

              Container container=getContentPane();

              container.setLayout(new BorderLayout());

              container.add(panel,BorderLayout.NORTH);

              container.add(scroller,BorderLayout.CENTER);

              container.add(jbtSave, BorderLayout.SOUTH);

 

              //Register listener

              jbtSave.addActionListener(this);container.add(

 

              //connect to server, get streams

              try{

 

                          //create Socket to make connection to server

                          connection=new Socket(InetAddress.getLocalHost(),5000);

 

                          //set up output stream

                          bufferOutput=new BufferedWriter(new OutputStreamWriter(

                                    connection.getOutputStream()));

 

                        //flush output buffer to send header information

                        bufferOutput.flush();

 

                        //set up input stream

                        bufferInput=new BufferedReader(new InputStreamReader(

                                    connection.getInputStream()));

 

             }

 

             //process problems communicating with server

             catch(IOException ioException){

                         ioException.printStackTrace();

     }

 

     setSize(500,500);

     show();

    }

 

    //process file name entered by user

    public void actionPerformed(ActionEvent event)

    {

                        //display contents of file

                        try{

                          String fileName=event.getActionCommand()+"\n";

                          bufferOutput.write(fileName,0,fileName.length());

 

                          bufferOutput.flush();

                          String output=bufferInput.readLine();

 

                          contents.setText(output);

 

                          //if file exists, display file contents

                          if(output.equals("The file is:")){

                                      output=bufferInput.readLine();

 

                                      while(output!=null){

                                contents.append(output+"\n");

                                output=bufferInput.readLine();

                              }

                             }

 

                                     fileField.setEditable(false);

                                     fileField.setBackground(Color.lightGray);

                                     fileField.removeActionListener(this);

 

                                     //close streams and socket

                                     bufferOutput.close();

                                     bufferInput.close();

                                     connection.close();

                            }

 

                            //end of file

                            catch(EOFException eofException){

                                                System.out.println("End of file");

                            }

 

                            //process problems communicating with server

                            catch(IOException ioException){

                                                ioException.printStackTrace();

                            }

                   }

 

                   //execute application

                   public static void main(String args[])

                   {

                                     Client application=new Client();

 

                                     application.setDefaultCloseOperation(

                                                 JFrame.EXIT_ON_CLOSE);

                            }

 

               }//end class Client

 

               public class RegistrationClient extends JApplet

                  implements ActionListener{

                                      //Button for registering a student in the file

                                      private JButton jbtRegister = new JButton("Save Changes");

 

                                      //Create a student information panel

                                      private StudentPanel studentPanel = new StudentPanel();

 

                                      //Indicate if it runs as applicatiuon

                                      private boolean isStandAlone = false;

 

                                      //Host name or ip

                                      private String host = "localhost";

 

                                      public void init(){

                                                  //Add the student panel and button to the applet

                                                  getContentPane().add(StudentPanel, BorderLayout.CENTER);

                                                  getContentPane().add(jbtRegister, BorderLayout.SOUTH);

 

                                                  //Register listenerjbtRegister.addActionListener(this);

                              }

 

                              /**Handle button action*/

                              public void actionPerformed(ActionEvent e){

                                                  if(e.getSour);

 

                                      //Get text field

                                      Student s = studentPanel.getStudent();

 

                                      //Get data from text fields and send it to the server

                                      toServer.println(s.getName());

                                      toServer.println(s.getStreet());

                                      toServer.println(s.getCity());

                              }

                            catch(ioException ex){

                                                System.err.println(ex);

                            }

                 }

      }

 

      /**Run the applet as an application */

      public static void main(String[] args{

                          //Create a frame

                          JFrame frame = new JFrame("Register Student Client");

 

                          //Create an instance of the applet

                          RegistrationClient applet = new RegistrationClient();

                          applet.isStandAlone = true;

 

                          //Get host

                          if (args.length == 1) applet.host = args[0];

 

                          //Add the applet instance to the frame

                          frame.getContentPane().add(applet, BorderLayout.CENTER);

 

                          //Invoke init() and start()

                          applet.init();

                          applet.start();

 

                          //Display the frame

                          frame.pack();

                          frame.setVisible();

               }

    }

 

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

OUTPUT