Tutorial: How to Create a Basic Multithreaded Client/Server Application III
by
Ronald S. Holland
Total Application Works
RonHolland@sumtotalz.com






To visit my site



To contact us

© 2002 - 2016 All Rights Reserved Total Application Works



  • Tell a friend about this site (copy and paste the following HTML page into a file or send this page to a friend.)
HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#
<html>
<title>Example of a link </title>
<body>
<table border>
<a href="http://www.sumtotalz.com/TotalAppsWorks/Multithreaded/MT_C_S_III_Tutorial.html">
MultithreadedClient Server Tutorial III </a>
</table>
</body>
</html>
Source
Screenshot

  • On-site classes can be arranged in Java and C++. Send all inquiries to:
    RonHolland@sumtotalz.com


  • If you are having a problem viewing your DVD/CD ROM using Vista, try Restoring DVD/CD ROM
  • Introduction
  • Requirements
  • What is the purpose of the setup() method?
  • Putting it all together to build a menu
  • Putting it all together to build the Record class
  • Putting it all together
  • RunServer() and run() Method modifications
  • Summary of tcpServer Methods
  • Outline of tcpClient Methods
  • Summary of tcpClient Methods
  • Definitions

    Introduction

    The purpose of the tutorial is to show you how to build a multithreaded client server application that responds to requests from clients that use either TCP/IP or HTTP protocols. In addition, we will change the array of addresses found in the MultiThreaded Client Server II Application to a file that contains persistent address data. Normally, TCP/IP is used with applications (programs with a main() method) and HTTP is used in calls from browsers. This tutorial shows you how to build a poor man's modified Tomcat. You might call it a student's version of Tomcat. The server we will build will not come close to having the functionality of Tomcat; however, it will help you start developing the theory behind the more complex servers. This tutorial assumes that you have read and completed the following tutorials.

    1. A Tutorial on MultiThreaded Client Server II Application
    2. Building a Basic Client/Server Application II
    In this tutorial, we will merge the Building a Basic Client/Server Application II and the MultiThreaded Client Server II Application into the Multithreaded Basic Client/Server III Application. We will not repeat the material covered in the previous tutorials 1 and 2 above. In this tutorial, we will show you how to increase the functionality of the server from the previous MultiThreaded Client Server II tutorial. We will not modify the Client from the previous tutorial in any way. All of our work in this tutorial will be in the tcpServer found in the Basic Client/Server Application II tutorial.

    Some other tutorials that may prove helpful are:

    1. Applet Life Cycle Tutorial
    2. Thread Life Cycle Tutorial
    3. MultiThreaded Program
    4. MultiThreaded Program
    5. Tutorial: Basic Client/Server Application
    6. A Tutorial on MultiThreaded Client Server Application
    7. Building a Basic Client/Server Application

    Requirements

    The requirements for this project are to:

    1. Use the application we developed in the tutorial, "Basic Client/Server Application II" as the basis for our multithreaded client/server III application.
    2. The server's GUI will remain the same. The GUI will have the following:
      1. ContentPane
      2. JButton
      3. JPanel
      4. BorderLayout Manager
      5. ActionListener
      6. JTextArea
      7. JScrollPane
    3. Use a setup() method for initialization. Realize that since the GUI is not changing in this example, the work in the setup() method is already done. We will use this method to reinforce the theory behind the Holland's OOP Programming Design Model. We will simply redirect the logic flow.
    4. Use Holland's OOP Programming Design Model to do the modification on the tcpServer class.
    5. The Basic Client/Server Application client-server structure that we are working from looks like:

        
      
                                     Java  
                                     API
                                   +------+
                                   |TCP/IP| 
                                   +---+--+
                                       |
        tcpClient               +---+  |  +---+        tcpServer
        Methods                 | S |  |  | S |        Methods
       +-------------------+    | o |  |  | o |    +-------------------+
       | tcpClient()       |<-->| c |  |  | c |<-->| tcpServer()       |
       +-------------------+    | k |  v  | k |    +-------------------+
       | setUp()           |    | e |<--->| e |    | setup()           |
       +-------------------+    | t |     | t |    +-------------------+
       | connect()         |    +---+     +---+    | RunClient()       |
       +-------------------+                       +-------------------+ 
       | RunServer()       |                       | closeConnection() | 
       +-------------------+                       +-------------------+ 
       | closeConnection() |                       | connect()         | 
       +-------------------+                       +-------------------+
       | main()            |                       | main()            |
       +-------------------+                       +-------------------+
                                                   |     Record        |
                                                   |  +-------------+  |
                                   +-------------> |  |    Read     |  |
                          +--------+----------+    |  +-------------+  | 
                          |  Address Data     |    |      ...          |
                          +--------+----------+    |  +-------------+  |
                                   +<------------- |  |  Write      |  | 
                                                   |  +-------------+  | 
                                                   +-------------------+ 
      
        
      Figure 1: Two-tier application


    6. Add an inner MyThread class, that extends the Thread class, to the tcpServer class.
    7. Add capabilities to respond to the following HTML pages:
      1. Helloworld
      2. HTTPGetServlet
      3. HTTPGetNames
    8. The process for responding to the browser client should resemble the following:

        
             +-----------------+        +-----------------+
             | Browser: Client |------->|     Server      |   
             +-----+-----------+        +--------+--------+
                   ^                             |
                   |                             |
                   |                       +-----+--------+
                   |                       |Filter Request|
                   |                       +-----+--------+
                   |                             |
                   |                             |
                   |                       +-----+--------+
                   |                       |  Respond to  |
                   |                       |    Request   |
                   |                       +-----+--------+
                   |                             |
             +-----+--------+                    |
             | Send Page to |<-------------------+                   
             |   Browser    |
             +--------------+                                         
                                               
        
      Figure 2: Architecture of Browser Request/Response


    Why do we use the setup() method specified in number 3 above? We will discuss this in the next section.

    What is the purpose of the setup() method?

    The purpose of the setup() method is for initialization. In the tcpServer application, the setup() method's purpose is to create any GUI that is displayed on the main frame. Remember, we are not changing the tcpServer GUI, so we already have some insights on the data and the behavior of the setup() method on this data. The data that the setup() method will work on is:

    1. Container c = getContentPane();
    2. JButton exit = new JButton( "Exit" );
        This is an implementation of a "push" button.
        Exit
    3. JPanel buttonPanel = new JPanel() ;
        JPanel is a generic lightweight container on which we will place the Exit button.
    4. Thread thrd = new Thread[ 15 ] ;
    5. JTextArea display = new JTextArea();
    In the above Figure 1, it appears that all of the initialization code is done in the constructor. For ease of readability and maintainability, I prefer to spread the initialization using finer logical units. With this thought in mind, the tcpServer() constructor's logic could look like:
    1. setupThreads()
    2. Setup()
      1. SetupMenu()
      2. SetupToolbar()
      3. SetupPanels()
      4. SetupArrays()
      5. SetupButtons()
      6. startThreads()
      7. show() - Makes the JFrame visible
    The above logic takes place in the tcpServer() constructor's. Instead of placing all of the initialization in the constructor, we have already performed several passes of step-wise refinement. If we had a:
    1. General initialization
    2. Menu
    3. Toolbar
    4. Multiple panels
    5. Multiple arrays
    6. Many buttons
    7. Multiple threads
    the outline/template would look like:

    tcpServer() Class
      
    public class tcpServer() {
       public tcpServer() {
    
          c = getContentPane() ;
    
          Setup() ;
    
          show() ;
    
       }
       private void Setup()  {   
    
          SetupMenu() ; 
    
          SetupToolbar() ;
    
          SetupPanels() ;
    
          SetupArrays() ;
    
          SetupButtons() ;
    
          setUpTextArea() ;
    
       }
       private void SetupMenu() {
          ...
       }
       private void SetupToolbar()  {
          ...
       }
       private void SetupPanels()  {
         ...
       }
       private SetupArrays()  {
          ...
       }
       private void SetupButtons()  {
          ...
       }
       private void SetUpTextArea()  {
          ...
       }
       private void startThreads() {
          ...
       }
       public static void main(String[] args) {
          ...
       }
    }
      
    Figure 3: setup() methods


    What just happened? The initialization that normally might have been performed in the constructor and the setup() method was broken down into the above methods found in Figure 3. This process is known as topdown programming. What I have done is take a unit (tcpServer() constructor), and I have broken it down into finer units. It is like taking a dime and turning it into ten pennies. The pennies are still worth ten cents, which is the same value of a dime. Even though I do this replacement in the context of the original constructor/Setup() method, this finer granularity makes it easier to see what I have done and what needs to be done. What we have done is break down the original constructor/setup() method into methods to handle specific tasks. As you do this stepwise refinement programming, don't be afraid to prototype what you are doing. The prototype allows you to evaluate your design, as you progress. Leonardo da Vinci probably evaluated the Mona Lisa as the painting progressed instead of waiting to the end. You don't want to wait to the end to find out what you are building doesn't work or is not what the customer wants. This process also allows you to test each method as you fill in the code. Don't wait until all of the code has been completed before starting the testing. I have seen projects fail because the integration of all of the code at the last minute was overwhelming.

    In object-oriented programming, programming revolves around the data. So in this style, the top is the data. It might be depicted as follows:

      
              +--------------+
              |      Data    |<----+  
              +-------+------+     | 
                      ^            |
                      |----------->+
                      V            ^
              +-------+------+     |
              |   Top-down   |     | 
              |  Structured  |<----+
              |  programming |     |
              |  on Classes  |     | (step-wise)
              |  and methods |     | (refinement)
              +--------------+     | (as needed) 
                      |            |
                      +------------+ 
     
      
    Figure 4: Holland's OOP Programming Design Model

    Putting it all together to build a menu

    How do we put it all together to build a menu? We will use the Holland's OOP Programming Design Model on a method and a set of data. Let's assume that we want to build the following menu:
    File Edit View Tools Help

    From previous experience and Figure 3: setup() methods, we know that we want to define the following data:

    1. JMenuBar bar
    2. JMenu file
    3. JMenu edit
    4. JMenu view
    5. JMenu tools
    6. JMenu help
    and we want the SetupMenu() method to work on the above data. Once we have this part working, we will want to add JMenuItems and possibly additional JMenus. Therefore, we will iterate on our definitions until we have completely defined the SetupMenu() method and the data on which it will operate. So, what steps did we go through to make this happen?
    1. Define and create a JMenuBar;
    2. Define and create the JMenus;
    3. Define and create any addition JMenus that will be child menus to other JMenus;
    4. Define and create the JMenuItems;
    5. Add the child menus, as appropriate, and JMenuItems to the appropriate JMenus;
    6. Add the JMenus to the JMenuBar.
    The above are the basic steps taken to create menus. You will notice that most menus look very similar. Therefore, you may want to consider finding/creating a method and layout you like and making a template/solution. It makes no sense to reinvent the wheel every time you want to build a menu. This template allows you modify the template to fit the design without spending a great deal of time on this part of your programming task. Keep in mind that your customer will have the final say on the layout. We can use similar methodology to make templates of the other Setup methods. How would we use this approach to build a class?

    Putting it all together to build the Record class

    How do we put it all together to build the Record class? Again, we will use the Holland's OOP Programming Design Model on a class and a set of data. Since we are building an address record, we will define data that will help us to uniquely identify an individual. The data will look like:

    1. int recID
    2. String firstName
    3. String lastName
    4. String address
    5. String city
    6. String state
    7. String zip
    8. String telephone
    9. String email
    For the data to be persistent, the data will need to reside in a file on a storage device. To access this data, we will need methods that read and write the data to the storage device. In addition, we will need methods that get and set the data. Our preliminary outline looks like:
      
    public class Record  {
    
          private int recID ;
          private String firstName ;
          private String lastName ;
          private String address ;
          private String city ;
          private String state ;
          private String zip ;
          private String telephone ;
          private String email ;
          private int ii = 0 ;
    
          public void ReadRec( RandomAccessFile file ) throws IOException
          {
    
          }
    
          public StringBuffer fill ( String str, StringBuffer buf ) {
    
    
          }
    
          public void write( RandomAccessFile file ) throws IOException
          {
    
          }
    
          public int getRecID() { return recID; }
    
          public String getFirstName() { return firstName.trim(); }
    
          public String getLastName() { return lastName.trim(); }
    
          public String getAddress() { return address.trim(); }
    
          public String getCity() { return city.trim(); }
    
          public String getState() { return state.trim(); }
    
          public String getZip() { return zip.trim(); }
    
          public String getTelephone() { return telephone.trim(); }
    
          public String getEmail() { return email.trim(); }
    
          public void setFirstName( String f ) { firstName = f; }
    
          public void setLastName( String f ) { lastName = f; }
    
          public void setAddress( String f ) { address = f; }
    
          public void setCity( String f ) { city = f; }
    
          public void setState( String f ) { state = f; }
    
          public void setZip( String f ) { zip = f; }
    
          public void setTelephone( String f ) { telephone = f; }
     
          public void setEmail( String f ) { email = f; }
    
     
          public void setRecID( int q ) { recID = q; }
    
           
          public int getSize() { return 752; }
       }
       /***************** End of Record Class *****************************/
      
    Figure 5: Template for how to build the Record class

    Putting it all together

    How do we put it all together?

    1. We will use the tcpServer class in the Building a Basic Client/Server Application II tutorial as our starting point.
    2. Define the setup() method for initialization.
        
      public  void setup() {
         c = getContentPane();
      
            SetupMenu() ; 
      
            SetupToolbar() ;
      
            SetupPanels() ;
      
            SetupArrays() ;
      
            SetupButtons() ;
      
            setUpTextArea() ;
      
         setSize( 400, 400 );
         setLocation( 10, 20 ) ;
         show();
      }
        
    3. Define the exit push button.
        
      public  void setUpButtons() {
         exit = new JButton( "Exit" );
         exit.setBackground( Color.red ) ;
         exit.setForeground( Color.white ) ;
      
         exit.addActionListener( this );
      }
        
    4. Define a panel to contain the exit push button.
        
      public  void setUpPanels() {
         buttonPanel = new JPanel() ;
         buttonPanel.add( exit ) ;
         c.add( buttonPanel , BorderLayout.SOUTH) ;
      }
        
    5. Define a text area to display messages.
        
      public  void setUpTextArea() {
      
         display = new JTextArea();
         display.setEditable( false );
         addWindowListener( new WindowHandler( this ) );
         c.add( new JScrollPane( display ),
                   BorderLayout.CENTER );
      }
        
    6. Set the size of the main frame.
        
      setSize( 400, 400 );
        
    7. Set the initial location of the main frame on the terminal.
        
      setLocation( 10, 20 ) ;
        
    8. Make the main frame visible on the main frame.
        
      show();
        
    Figure 5: Template for how to build the Record class


    At this point, are we finished with this tutorial? The answer is no! All we have done is create the GUI objects in the setup() method. Remember the setup() method is called from the constructor and this call is made once during initialization. When we refer to Holland's OOP Programming Design Model, we see the relationship between the GUI, which is the data, and the method, which is the setup() method. The purpose of this tutorial was to create a multithreaded server. The Basic Client/Server Application II is a single threaded application. We will modify the RunServer() method so that it creates a new thread when a new client connects to the server.

    RunServer() and run() Method modifications

    In the RunServer() method, the data being manipulated is:

    1. server_socket - a ServerSocket object
        Listens for a Client connection to be made to this socket and accepts it. When the accept() method of ServerSocket is called, it returns a new Socket object that represents a new client connection that has attached to the server. Until a client attempts to connect, this method waits/listens. When a successful connection is made, a Socket object is returned.
    2. display - a JTextArea object
    3. socket - a Socket object
        This class implements client sockets. A socket is an endpoint for communication between two machines. The ServerSocket.accept() method returns a Socket object when there has been a successful connection.
    4. input - a BufferedReader object, which reads text from a character-input stream
      • getInputStream() returns a stream object that can be used to communicate through the socket.
    5. request - a MyThread object
    6. thrd - a Thread object
    The request and thrd objects are new in this modification. MyThread's run() method has become the workhorse method of this application. The data and method relationship should be obvious. When a successful client connection is made, a new Thread object is created and started. In the tutorial on Building a Basic Client/Server II Application, an outline of the logic in the RunServer() method looked like:
      
    try {
       while(true) {
          try {  // inner try construct
             while(true) {  // inner while construct
                ...
             }
          }
       }
    }
      
    In this tutorial, the above inner try and while constructs have been moved to MyThread's run() method.

    In this tutorial, an outline of the RunServer() method looks like:

      
    try {
       while(true) {
          ...
       }
    }
      
    and the MyThread's run() method looks like:
      
    try {  // previously the inner try construct
       while(true) {  // previously the inner while construct
          ...
       }
    }
      
    Figure 6: RunServer() and run() Method modifications


    In the following section, we will see an ourline of the tcpServer class Methods.

    Summary of tcpServer Methods

    The outline of the tcpServer class looks like:

      
    
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    
    /** **************************************************************
     * The tcpServer class defines the framework for creating a server
     * based multithreaded application. The server responds to request 
     * from a Client. The purpose of the tcpServer class is to create 
     * a server that 
     *  1- Creates a server main frame
     *  2- Establishes a server socker
     *  3- Accepts clients in a multithreaded environment
     ****************************************************************/
    public class tcpServer extends JFrame implements  ActionListener {
        
    
       /** **************************************************************
         * This is the tcpServer constructor which is used to
         * initialize the tcpServer() object.
        ****************************************************************/
        public  tcpServer() {
           
        }
    
        /**  **************************************************************
         * The setThreadcount() method resets the thread count.
         ****************************************************************/
        public  void setThreadcount( int a ) {
            
        }
    
        public  void setup() {
    
          SetupMenu() ; 
    
          SetupToolbar() ;
    
          SetupPanels() ;
    
          SetupArrays() ;
    
          SetupButtons() ;
    
          setUpTextArea() ;
    
          
        }
    
        /**  **************************************************************
         * The setThreadcount() method resets the thread count.
         ****************************************************************/
        public  void setThreadcount( int a ) {
           trdCnt = a ;
        }
    
    
       /**  ******************************************************************
        * The setupThreads() method
        *********************************************************************/
        public void setupThreads() {
    
          thrd = new Thread[ 15 ] ;
        }
    
        /**  **************************************************************
         * The setUp() method does the intializes the application's
         * 1- JButtons
         * 2- JPanel
         * 3- JTextArea
         * 4- Set the size
         * 5- Set the location of the application on the screen
         * 6- Make the application visiable
         *
         ****************************************************************/
        public  void setup() {
    
        }
    
        /** *********************************************************
         * The setUpTextArea() method
         * 1- Creates the display JTextArea
         * 2- Adds a ScrollPane( to the display TextArea
         ************************************************************/
        public  void setUpTextArea() {
          
        }
    
        /** *********************************************************
         * The setUpPanels() method
         * 1- Creates the buttonPanel JPanel
         * 2- Adds the exit button to the buttonPanel
         * 3- Adds the buttonPanel southern part of the content pane
         ************************************************************/
        public  void setUpPanels() {
          
        }
    
        /** *********************************************************
         * The setUpButtons() method
         * 1- Creates the exit JButton
         * 2- Sets the background color
         * 3- Sets the foreground color
         * 4- Add an ActionListener to the exit button
         ************************************************************/
        public  void setUpButtons() {
          
        }
    
       /**  ******************************************************************
        * The RunServer() method in the server reads and writes data to the
        * client. the logic for the ServerRun() method is
        *  1- Create a ServerSocket object
        *  2- Create messages and display them in the text area.
        *  3- Loop while waiting for Client connections.
        *  4- Call ServerSocket accept() method and listen.
        *  5- Create an InputStreamReader based on the socket.getInputStream() object
        *  6- Create a BufferedReader based on the  InputStreamReader object
        *  7- Create a new MyThread object
        *  8- Start the new MyThread object
        *********************************************************************/
        public void RunServer() {
           try {
                   
              while( loopCTL ) {
                                
                       // Construct handler to process the Client request message.
                 try {
                                  
                 }
                 catch(Exception e) {
                   	       
                 }
              }   // End of while loop
                   
           }
           catch (IOException e) {
               
           }
        }
    
       /** *********************************************************
        * This method responds to the exit button being pressed
        * on the tcpServer frame.
        *************************************************************/
       public void actionPerformed( ActionEvent e )    {
          if ( e.getSource() == exit )
              
       }
    
       /**  ****************************************************************
        * This method closes the socket connect to the server.
         *******************************************************************/
       private void closeConnection() {
          
       }
    
       /** ***********************************************************
        * The sysExit() method is called in response to a close
        * application event.
        ************************************************************* */
       public void sysExit( int ext ) {
          l
       }
    
       /** ***********************************************************
        * The sysPrint method prints out debugging messages.
        ************************************************************ */
       public void sysPrint( String str ) {
          
       }
    
       /** ***********************************************************
        * The main() is called by Java when the tcpServer program is
        *  loaded.
        ************************************************************ */
        public static void main(String args[]) {
           
        }
    
       /** ********************************************************
        * This method closes the socket connect to the server when the
        * application window is closed.
        ********************************************************  */
       public class WindowHandler extends WindowAdapter {
          tcpServer tcpS;
    
          public WindowHandler( tcpServer t ) { tcpS = t; }
    
          public void windowClosing( WindowEvent e ) { tcpS.closeConnection(); }
       }
    }
      
    Figure 7: Summary of tcpServer Class Methods


    A summary of the tcpServer Methods is shown in the following figure.

    Summary of tcpServer Methods
    Method Description
    actionPerformed() The actionPerformed() method is an event handler that responds to the exit button being pressed on the tcpServer frame.
    closeConnection() is used to close the socket connection and the input/output streams.
    InitRecord() The InitRecord() method is called to initialize the address.dat file,
    main() he main() method is the entry point the Java calls when for the server application is loaded into memory.
    RunServer() The RunServer() method is used to create the
    1. Server socket, input/output streams
    2. NewThreads
    3. BufferedReader
      • Based on InputStreamReader
    4. New PrintWriter
      • Based the Server socket getOutputStream() method
    5. Starts the new threads
    setThreadcount() The setThreadcount() method resets the thread count.
    setUp() The setUp() method does the intializes the application's
    1. JButtons
    2. JPanel
    3. JTextArea
    4. Set the size
    5. Set the location of the application on the screen
    6. Make the application visiable
    SetupArrays() In the SetupArrays() method, the arrays are created.
    setUpButtons() The setUpButtons() method
    1. Creates the exit JButton
    2. Sets the background color
    3. Sets the foreground color
    4. Add an ActionListener to the exit button
    SetupMenu() In the SetupMenu() method, the menubar and menuitems are created.
    setUpPanels() The setUpTextArea() method
    1. Creates the display JTextArea
    2. Adds a ScrollPane( to the display TextArea
    setUpTextArea() The setUpTextArea() method
    1. Creates the display JTextArea
    2. Adds a ScrollPane( to the display TextArea
    setupThreads() The setupThreads() method creates a Thread array.
    SetupToolbar() In the SetupToolbar() method, the toolbar and any toolbar items are created.
    sysExit() The sysExit() method is called in response to a close application event.
    sysPrint() TThe sysPrint method prints out debugging messages.
    tcpServer() this is the class constructor used for initialization.
    Figure 8: Summary of tcpServer Methods


    Summary of tcpServer Inner Class MyThread

    The outline of the tcpServer's inner MyThread class looks like:

      
    
       /** ***********************************************************
        *  The purpose of the MyThread class is to create a thread of
        *  execution to respond to client requests.  A thread is a
        *  thread of execution in a program. The Java Virtual Machine
        *  allows an application to have multiple threads of execution
        *  running concurrently.
        **************************************************************/
       public class MyThread extends Thread {
          
    
          /** *********************************************************
           * The purpose of the MyThread() constructor is to used the
           * passed parameters to initialize MyThread class level
           * variables.
           **************************************************************/
          public MyThread( tcpServer tps , Socket socket , int trd_Cnt ) throws Exception {
             
          }
    
          /** *********************************************************
           * The run() method responds to the client's request.
           **************************************************************/
          public void run() {
             
             try {
                while(  !message.toUpperCase().equals( "QUIT" ) ) {
                   if ( tokens.countTokens() >= 1 )   {
                      if( message.equals( hWorld ) ) {  
                      }   
    	          else if( message.equals( gServ ) ) {   
                      }    
                      else if( message.equals( gNames ) ) {  
                      }    
                      if ( messageTokens[ 0 ].toUpperCase().equals( "GET" ) ) { 
                         }
                         else if ( messageTokens[ 0 ].toUpperCase().equals( "FIND" ) ) 
                         }
                         else if ( messageTokens[ 0 ].toUpperCase().equals( "LISTALL" ) ) {
                         } 
                         else if ( messageTokens[ 0 ].toUpperCase().equals( "ADD" ) ) {  
                         }
                         else if ( messageTokens[ 0 ].toUpperCase().equals( "UPDATE" ) ) {  
                         }
                         else if ( messageTokens[ 0 ].toUpperCase().equals( "DELETE" ) ) { 
                         }
                      }  
                   }  
                }
             }
             catch(Exception e) {
                 
             }
          }
    
       }
      
    Figure 9: Outline of tcpServer Inner Class MyThread


    In the next figure, we show a summary of the innner Class MyThread Methods.

    Method Description
    MyThread The purpose of the MyThread() constructor is to used the passed parameters to initialize MyThread class level variables.
    run() The run() method responds to the client's request.
    Figure 10: Summary of Inner Class MyThread Methods

    Outline of tcpClient Methods

    An outline of tcpClient Methods are shown below.

     import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.awt.event.*;
    import java.util.*;
    import java.net.*;
    
    /** ***************************************************************
      * The tcpClient class creates an object for the Client frame.
      * Set up a client that will receive
      *    - a connection from a server
      *      - sends requests for services to the Server
      *        - Send
      *
      *    - process server responses to string(s) sent back to the client
      *    - and close the connection when the Client is finished.
      *
     ******************************************************************/
    public class tcpClient extends JFrame implements  ActionListener {
    
    
       /** ***************************************************************
        *  The tcpClient constructor initializes the tcpClient object.
        ******************************************************************/
       public tcpClient() {
          super( "Client" ) ;
    
          setUp() ;
    
          connect() ;
    
          RunClient() ;
    
          closeConnection() ;
       }
    
       /** ***************************************************************
        * The setUp() method does the intialization for the application.
        * The setUp() method
        * 1- Creates JButtons
        * 2- Creates JPanels
        * 3- Creates JLabels
        * 4- Adds Action Listeners to the JButtons
        * 5- Sets the size for the JFrame
        * 6- Sets the location for the JFrame
        * 7- Makes the JFrame visible
        ******************************************************************/
       public  void setUp() {
    
       }
    
       /** ***************************************************************
        * The setUpButtons() method
        * 1- Creates the JButtons
        * 2- Sets the Background color
        * 3- Sets the Foreground color
        * 4- Adds an ActionListener  to the JButtons
        ***************************************************************** */
       public void setUpButtons() {
    
       }
    
       /** ***************************************************************
        * The setUpLabText() method creates
        * 1- The enterLabel JLabel
        * 2- The enterBox JTextField for user input
        * 3- The textPanel JPanel
        * 4- Attaches the GridLayout manager to the textPanel JPanel
        * 5- Adds textPanel to the northern part of the content pane
        * 6- Creates the display JTextArea
        * 7- Adds the display JTextArea center of the content pane
        ***************************************************************** */
       public void setUpLabText() {
    
       }
    
       /** *****************************************************************
        *  The connect() method does the intialization of the client socket
        *  on localhost and port 5050
        ***************************************************************** */
       public void connect() {
    
       }
    
       /** *****************************************************************
        * The sendData() method in the client sends data to the server
        ***************************************************************** */
       public void sendData(String str) {
           
       }
    
    
       /** *****************************************************************
        * The RunClient() method in the client reads and writes data to the server.
        ***************************************************************** */
       public void RunClient() {   
    
       }
    
       /** *****************************************************************
        * This method responds to the find, delete, clear or exit button
        *  being pressed on the tcpClient frame.
        ***************************************************************** */
       public void actionPerformed( ActionEvent e )    {
    
       }
    
       /*******************************************************************
        * This method shows the name found by the server.
        ***************************************************************** */
       public  void showName() {
      
       }
    
       /** *****************************************************************
        * This method lists all of the name found by the server.
        ***************************************************************** */
       public  void listNames() {
     
       }
    
       /** *****************************************************************
        * This method closes the socket connect to the server.
        ***************************************************************** */
       public  void closeConnection() {
     
       }
    
       /** *****************************************************************
        * This method is the main entry point called by the JVM.
        ****************************************************************** */
       public static void main(String[] args) {
     
       }
    
       /** *****************************************************************
        * This method closes the socket connect to the server when the
        * application window is closed.
        ***************************************************************** */
       public class WindowHandler extends WindowAdapter {
          tcpClient tcpC;
    
          public WindowHandler( tcpClient t ) { tcpC = t; }
    
          public void windowClosing( WindowEvent e ) { tcpC.closeConnection(); }
       }
    
    }
     
    Figure 11: Outline of tcpClient Methods

    Summary of tcpClient Methods

    The Summary of tcpClient Methods are shown below.

    Summary of tcpClient Methods
    Method Description
    actionPerformed() This method responds to the send, clear, or exit buttons being pressed on the tcpClient frame.
    closeConnection() is used to close the socket connection and the input/output streams.
    connect() this method is used to connect to the socket.
    listNames() This method lists all of the name found by the server.
    main() This method is the main entry point called by the JVM.
    runClient() this method is used to
    1. Create input/output streams
    2. Make requests of the server in the form of messages sent to the server
    3. Listen for input from the socket.
    sendData() The sendData() method in the client sends data/requests to the server.
    setUp() this method is used to setup and allocate the GUI objects.
    SetupArrays() In the SetupArrays() method, the arrays are created.
    setUpButtons() The setUpButtons() method
    1. Creates the JButtons
    2. Sets the Background color
    3. Sets the Foreground color
    4. Adds an ActionListener to the JButtons
    SetupMenu() In the SetupMenu() method, the menubar and menuitems are created.
    SetupPanels() The setUpTextArea() method
    1. Creates the buttonPanel JPanel
    2. Adds the exit button to the buttonPanel
    3. Adds the buttonPanel southern part of the content panel
    setUpLabText() The setUpLabText() method creates
    1. The enterLabel JLabel
    2. The enterBox JTextField for user input
    3. The textPanel JPanel
    4. Attaches the GridLayout manager to the textPanel JPanel
    5. Adds textPanel to the northern part of the content pane
    6. Creates the display JTextArea 7- Adds the display JTextArea center of the content pane
    showName() This method shows the name found by the server.
    sysExit() The sysExit() method is called in response to a close application event.
    sysPrint() The sysPrint method prints out debugging messages.
    tcpClient() this is the class constructor used for initialization.
    Figure 12: tcpClient Methods


    Definitions

    applet

      is a program designed to be executed from within another application, such as a browser like Netscape. An applet is different from an application. Applets cannot be executed directly from the operating system like an application.

    application server

      Also called an appserver. A program that handles all application operations between users and an organization's backend business applications or databases. Application servers are typically used for complex transaction-based applications. To support high-end needs, an application server has to have built-in redundancy, monitors for high-availability, high-performance distributed application services and support for complex database access.

      Sometimes referred to as a type of middleware, application servers occupy a large chunk of computing territory between database servers and the end user, and they often connect the two. However, don't limit yourself to traditional database programs. Once you visualize airport management packages, you can start to visualize the only limit is your imagination.

    Apache Tomcat

      is the servlet container that is used in the official Reference Implementation for the Java Servlet and JavaServer Pages technologies. Tomcat is a servlet container that can be used as a web server.

    asynchronous

      Most communication between computers and devices is asynchronous -- it can occur at any time and at irregular intervals. Communication within a computer, however, is usually synchronous and is governed by the microprocessor clock. Signals along the bus, for example, can occur only at specific points in the clock cycle.

    concurrently

      In programming, this refers to the ability of multiple programs running at the same time. This can only happen if there are multiple processors. If there is one processor, then the programs are timeslicing.

    distributed processing

      Refers to any of a variety of computer system configurations that comprise more than one computer/processor to run an application. This includes parallel processing or multiprocessing, in which a single computer uses more than one CPU to execute programs. More often, however, distributed processing refers to local-area networks (LANs) designed so that a single program can run simultaneously on various computers at one site or at various sites. Most distributed processing systems contain sophisticated software that detects idle CPUs on the network and parcels out programs to utilize them.

      Another form of distributed processing involves distributed databases, databases in which the data is stored across two or more computer systems. The database system keeps track of where the data is so that the distributed nature of the database is not apparent to users.

    HTTP

      Short for HyperText Transfer Protocol, the underlying protocol used by the World Wide Web. HTTP defines how messages are formatted and transmitted, and what actions Web servers and browsers should take in response to various commands. For example, when you enter a URL in your browser, this actually sends an HTTP command to the Web server directing it to fetch and transmit the requested Web page.

    JSP

      An extensible Web technology that uses template data, custom elements, scripting languages, and server-side Java objects to return dynamic content to a client. Typically the template data is HTML or XML elements, and in many cases the client is a Web browser.

    modal window

      A modal window is any type of window that is a child (secondary window, dialog) to a parent window and must run to completion or exit before returning control to the parent. This means that no other window can be accessed while this secondary window is active. An example of this is the Save dialog in a text editor.

    modeless window

      Similar to a modal window as it is a secondary window (i.e., child, dialog) that stays active on the user's screen until exited. Modeless windows can be minimized or hidden behind other windows. Unlike a modal window, a modeless window allows the user to continue accessing other windows (parent window) while the modeless window is open.

    multiprocessing

      Refers to a computer system's ability to support more than one process (program) at the same time. Multiprocessing operating systems enable several programs to run concurrently.

      Multiprocessing or multiple processors involves more than one processor. Multiprocessing is not the same as multitasking/multithreading. Java supports multitasking/multithreading. The Windows operating system supports multitasking/multithreading. Windows does not support multiprocessing.

    multithreading

      This is the capability of an operating system to execute different parts of a program, called threads, simultaneously. In reality, these threads run on a single processor, and these threads do not run at the same time or simultaneously. In effect, these threads are timeslicing. On a single processor, only one program can be running at a time. The programmer must carefully design the program in such a way that all the threads can timeslice without interfering with each other.

    n-tier -

    
                                   Tier 3
                                  +---------+
                               +->| Printer |
                               |  +---------+
                               |
      Tier 1        Tier 2     |    Tier 4
    +--------+     +--------+  |  +------+
    | Client |<--->| Server |<-+->| DBMS |
    +--------+     +--------+  |  +------+
       GUI         Application .     DB
                    Server     . 
                               .    Tier n
                               |  +---------+
                               +->| whatever|
                                  +---------+                           
     

    persistent data

      is data that is stored and accessed from storage media such as hard drives, diskettes, jump drives, and/or R/W Cds, etc..

    process

      A process is an executing program. An example could be a running text editor, word processor, or a browser.

    realtime

      Real-time processing is the application of hardware and software systems that are subject to a "real-time constraint"—i.e., operational deadlines from stimuli/data input to output or the system response to that stimuli.

    stepwise refinement

      Is a design process whereby a task is defined at a high level and is iterated on until the lower level of detail required for implementation is reached. For example, if we start with the outline in Figure 9 and proceed with stepwise refinement, the process might look like:

      An Example of Stepwise refinement
        
      +-------------------------------+
      |public class HardwareStore() { |
      |                               |
      |}                              |
      +-------------+-----------------+
                    |
                    |
                    V
      +-------------------------------+
      |public class HardwareStore() { |
      |   public HardwareStore()   {  |
      |      setup() ;                |
      |   }                           |
      |}                              |
      +-------------+-----------------+
                    |
                    |
                    V
      +-------------------------------+
      |public class HardwareStore() { |
      |   public HardwareStore()   {  |
      |      setup() ;                |
      |   }                           |
      |   setup() {                   |
      |                               |
      |      SetupMenu() ;            |
      |                               |
      |      SetupPanels() ;          | 
      |                               |
      |      SetupButtons() :         |
      |   }                           |
      |}                              |
      +-------------+-----------------+
                    |
                    |
                    V
      +-------------------------------+
      |public class HardwareStore() { |
      |   public HardwareStore()   {  |
      |      setup() ;                |
      |   }                           |
      |   setup() {                   |
      |                               |
      |      SetupMenu() ;            |
      |                               |
      |      SetupPanels() ;          | 
      |                               |
      |      SetupButtons() :         |
      |   }                           |
      |   public SetupMenu() {        |
      |   }                           |  
      |   public SetupPanels() ;      |
      |   }                           |  
      |   public SetupButtons() ;     |
      |   }                           |
      |   public static void          |
      |       main(String[] args) {   |
      |}                              |
      +-------------+-----------------+
                    |
                    |
                    V
                   ...
         
      Figure 13:


      If you compare Figure 8 with Figure 3 and then look at the tcpServer's SetupButtons() method, you can see where the stepwise refinement is going. You'll notice that you can start your template with Figure 3, change the class and constructor names to the name of your new class, and you have a starting point for your next project.

      Some programmers prefer pseudocode to flowcharts because pseudocode is self-documenting. I use flowcharts for tutorials because they are worth a thousand words, and I use pseudocode for my designs.

    structured programming

      A process in programming where the programmer divides his program's source code into logically structured chunks of code. This process is also known as stepwise refinement.

    synchronous - Means that an event occurs at regular intervals. The opposite of synchronous is asynchronous.

    TCP

      Abbreviation of Transmission Control Protocol, and pronounced as separate letters. TCP is one of the main protocols in TCP/IP networks. Whereas the IP protocol deals only with packets, TCP enables two hosts to establish a connection and exchange streams of data. TCP guarantees delivery of data and also guarantees that packets will be delivered in the same order in which they were sent.

    template - establishes or serves as a pattern.

    top-down programming

      A process in programming that begins with a general task and divides the general task into more specific tasks. At the top level of the program/class there is only the general task. For example, if you are tasked to build a Hardware Inventory application that extends JFrame, you might start with the following:

      Outline for a Hardware Store Inventory Program
        
      /** ************************************************************ 
       * In the HardwareStore class, the following take place. There is    
       * a class to:
       * 1- Password protect adds, updates, and deletes.
       * 2- List all entries in a table.
       * 3- Update a record in a table.
       * 4- Add a record to a table.
       * 5- Delete a record from a table.
       * 6- Gather data on a purchase.
       * 7- Add items to a shopping cart.
       * 8- Gather data on a customer.
       * 9- Contain the data for a record.
       *
       **************************************************************/
      public class HardwareStore extends JFrame
                implements ActionListener {
      
         public HardwareStore()   {
      
         }
      
         public static void main( String args[] )
         {
      
         }
      
         public class PassWord  extends Dialog
               implements ActionListener 
         public class ListRecs extends Dialog
               implements ActionListener  
      
         public class ListRecs extends Dialog
               implements ActionListener  
      
         public class UpdateRec extends Dialog
               implements ActionListener  
         public class NewRec extends Dialog
              implements ActionListener  
         public class DeleteRec extends Dialog
                implements ActionListener  
      
         public class BuyRec extends Dialog
               implements ActionListener  
         public class ShoppingCart extends Dialog
               implements ActionListener  
         public class Customer  extends Dialog
               implements ActionListener  
         public public class Record  
      }
         
      Figure 14:


      As the program code evolves or as you stepwise refine, the programming becomes more and more detailed.

    thread

      In programming, this refers to a part of a program that can execute concurrently with and independently of other parts of the program.

    timeslicing

      In programming, this refers to how the operating system parcels out time for the various programs to run/execute. This is usually done on a priority basis, with the operating system having the highest priority. Requests for system services usually result in a program/thread yielding its execution time and going into a wait state. When this happens, the operating system grants another program/thread execution time. In some systems, a program/thread is allocated a certain amount of time. When this time period is reached, the program/thread must yield to another program/thread.

    Two-tier - A client/server architecture where the GUI runs on the client and the business logic runs on the server.
    
      Tier 1        Tier 2         
    +--------+     +--------+     
    | Client |<--->| Server |
    +--------+     +--------+     
       GUI         |Business|    
                   |Logic   |       
                   +--------+               
     
    Figure 15: Two-Tier client/server


    Three-tier - A client/server architecture consisting of three well-defined and separate processes.
    
      Tier 1        Tier 2         Tier 3
    +--------+     +--------+     +------+
    | Client |<--->| Server |<--->| DBMS |
    +--------+     +--------+     +------+
       GUI          Application      DB
                    Server 
     
    Figure 16: Three-Tier client/server







  • © 2002 - 2010 All Rights Reserved Total Application Works

    HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#

    blog counter