Home : Course Map : Chapter 14 :
Client Application
JavaTech
Course Map
Chapter 14

Web Servers
Design of Server
ServerSocket
Threads For Clients
Client Streams
HTTP Protocol
Run Server
  Demo 1
Secure Server
  Demo 2
More Security
A client application
  Demo 3
Server Apps
Servlets
Exercises

     About JavaTech
     Codes List
     Exercises
     Feedback
     References
     Resources
     Tips
     Topic Index
     Course Guide
     What's New

Perhaps we don't want to bother with a browser to communicate with our web server. With the java.net resources it's easy to create a simple standalone client application that contacts the server, requests files and reads them.

Our client app could also interact in other ways. For example, maybe the client sends a command to the server to instruct it to carry out some action on the local platform such as running a diagnostic program. (See Chapter 23 for a discussion of running external programs from within a Java program.)

As we see in the next chapter, we can even maintain a connection with the client indefinitely and avoid the stateless condition of the usual browser-server interaction.

The application ClientApp shown below provides a graphical interface with which the user can enter the IP address and port for the server and then enther the name of the file to request from the server. With a thread process it will connect to the server, download the file, and display it in a text area.

It connects to the server by the creation of a Socket instance with the server's address and port number. Using the input and output streams obtained from the socket, the client sends a request to the server and then reads the data returned by the server one line at a time. The client then displays this data in a text area.

ClientApp.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

/**
  * This program provides a graphical user interface to
  * set up the connection to a server and to download
  * the file from the server and display it in a text area.
**/
public class ClientApp extends JFrame
       implements Runnable, ActionListener
{

  // Menu item names
  JMenuItem fMenuSave  = null;
  JMenuItem fMenuClose = null;

  //
  JTextArea  fTextArea = null;

  JTextField fIpField;
  JTextField fPortField;
  JTextField fFileField;

  // Default address is local
  String fIpAddr = "127.0.0.1";

  // Default port
  int fPort = 2222;

  // Socket to connect with server.
  Socket fSocket = null;

  // File name
  String fFilename = "message.html";

  // Change the button name as needed
  String fButtonName = "Get";
  JButton fButton = null;

  // Filter and File object for file chooser
  HtmlFilter fHtmlFilter = new HtmlFilter ();
  File fFile = new File ("default.html");

  Thread fThread = null;

  /** Start the program. **/
  public static void main (String [] args) {
    ClientApp f =
      new ClientApp ("Client for MicroServer ");
    f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
  }

  /**
    * Create user interface for client. Includes text fields
    * for the server IP address, the server's port number, a
    * text area to show the data returned from the server, and
    * a button to initiate the connection to the server.
   **/
  ClientApp (String title){
    super (title);

    Container content_pane = getContentPane ();

    // Create a user interface.
    content_pane.setLayout ( new BorderLayout () );
    fTextArea = new JTextArea ("");
    fTextArea.setLineWrap (true);

    content_pane.add ( fTextArea, "Center");

    // Create a panel with three text fields to obtain
    // the server address, the port number,
    // the file to download, and to initiate the link
    //  with the server.
    fIpField = new JTextField (fIpAddr);
    fPortField = new JTextField (""+fPort);
    fFileField= new JTextField (fFilename);

    // Button to initiate the download from the server
    fButton = new JButton (fButtonName);
    fButton.addActionListener (this);

    JPanel panel = new JPanel (new GridLayout (2,2));
    panel.add (fIpField);
    panel.add (fPortField);
    panel.add (fFileField);
    panel.add (fButton);

    content_pane.add ( panel, "South");

    // Use the helper method makeMenuItem
    // for making the menu items and registering
    // their listener.
    JMenu m = new JMenu ("File");

    // File handling.
    m.add (fMenuSave  = makeMenuItem ("Save"));
    m.add (fMenuClose = makeMenuItem ("Quit"));

    JMenuBar mb = new JMenuBar ();
    mb.add (m);

    setJMenuBar (mb);
    setSize (400,400);

    setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
  } // ctor

  /** Process events from the frame menu and the chooser.**/
  public void actionPerformed ( ActionEvent e ){
    boolean status = false;
    String command = e.getActionCommand ();

    if (command.equals (fButtonName) ) {

      // First get the server address
      fIpAddr = fIpField.getText ();

      // Get port number
      fPort = Integer.parseInt (fPortField.getText ());

      // Get the name of the file to download
      fFilename = fFileField.getText ();

      start ();

    } else if (command.equals ("Save") ) {
      // Save a file
      status = saveFile ();
      if ( !status)
          JOptionPane.showMessageDialog (
            null,
            "IO error in saving file!!", "File Save Error",
            JOptionPane.ERROR_MESSAGE);


    } else if (command.equals ("Quit") ){
      dispose ();
    }
  } // actionPerformed

  /**
   * Start the thread to connect to the server
   * and read the file from it.
   */
  public void start (){

    // If the thread reference not null then a
    // thread is already running. Otherwise, create
    // a thread and start it.
    if (fThread == null) {
        fThread = new Thread (this);
        fThread.start ();
    }
  } // start

  /** Connect with the server via a thread process. **/
  public void run () {

    // Clear the text area
    fTextArea.setText ("Downloading...");

    try{
      // Connect to the server via the given IP address and port number
      fSocket = new Socket (fIpAddr, fPort);

      // Assemble the message line.
      String message = "GET /" + fFilename;

      // Now get an output stream to the server.
      OutputStream server_out = fSocket.getOutputStream ();

      // Wrap in writer classes
      PrintWriter pw_server_out = new PrintWriter (
        new OutputStreamWriter (server_out, "8859_1"), true );

      // Send the message to the server
      pw_server_out.println (message);

      // Get the input stream from the server and then
      // wrap the stream in two wrappers.
      BufferedReader server_reader = new BufferedReader (
        new InputStreamReader ( fSocket.getInputStream () )  );

      fTextArea.setText ("");
      String line;
      // Add the text one line at a time from the server
      // to the text area.
      while  ((line = server_reader.readLine ()) != null )
        fTextArea.append (line + '\n');

    } catch  ( UnknownHostException uhe) {
      fTextArea.setText ("Unknown host");

    } catch  ( IOException ioe){
      fTextArea.setText ("I/O Exception");
    } finally{
      try{
        // End the connection
        fSocket.close ();
        fThread=null;
      } catch ( IOException ioe) {
        fTextArea.append ("IO Exception while closing socket");
      }
    }
  } // run

  /**
    * This "helper method" makes a menu item and then
    * registers this object as a listener to it.
   **/
  private JMenuItem makeMenuItem (String name) {
    JMenuItem m = new JMenuItem ( name );
    m.addActionListener ( this );
    return m;
  }

  /**
    * Use a JFileChooser in Save mode to select files
    * to open. Use a filter for FileFilter subclass to select
    * for *.java files. If a file is selected, then write the
    * the string from the text area into it.
   **/
  boolean saveFile () {

    File file = null;
    JFileChooser fc = new JFileChooser ();

    // Start in current directory
    fc.setCurrentDirectory (new File ("."));

    // Set filter for web pages.
    fc.setFileFilter (fHtmlFilter);

    // Set to a default name for save.
    fc.setSelectedFile (file);

    // Open chooser dialog
    int result = fc.showSaveDialog (this);

    if (result == JFileChooser.CANCEL_OPTION) {
      return true;
    }else if (result == JFileChooser.APPROVE_OPTION) {
        file = fc.getSelectedFile ();
        if (file.exists ()) {
            int response = JOptionPane.showConfirmDialog (null,
                "Overwrite existing file?","Confirm Overwrite",
                 JOptionPane.OK_CANCEL_OPTION,
                 JOptionPane.QUESTION_MESSAGE);
            if (response == JOptionPane.CANCEL_OPTION) return false;
        }
        return writeFile (file, fTextArea.getText ());
     } else  {
        return false;
     }
  } // saveFile

  /**
    * Use a PrintWriter wrapped around a BufferedWriter, which in turn
    * is wrapped around a FileWriter, to write the string data to the
    * given file.
   **/
  public static boolean writeFile (File file, String data_string){

    try {
         PrintWriter out =
           new PrintWriter (new BufferedWriter (new FileWriter (file)));
         out.print (data_string);
         out.flush ();
         out.close ();
    }catch  (IOException e) {
         return false;
    }
    return true;
  }
} // class ClientApp


/** Class to use with JFileChooser for selecting hypertext files.**/
class HtmlFilter extends javax.swing.filechooser.FileFilter{

  public boolean accept (File f){
    return f.getName ().toLowerCase ().endsWith (".htm")
        || f.getName ().toLowerCase ().endsWith (".html")
        || f.isDirectory ();
  }

  public String getDescription (){
    return "Web pages  (*.htm*)";
  }
} // class HtmlFilter


On a Windows machine the MicroSever and the ClientApp appear as shown here:

In Chapter 15 we will develop a more elaborate set of server-client programs.

 

Latest update: Dec. 9, 2004
  
  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
21
22 23 24
Supplements

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.