Tutorial: Basic Client/Server Application III


by
Ronald S. Holland
Total Application Works
RonHolland@sumtotalz.com






To visit my Site

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


To contact us

© 2002 - 2011 All Rights Reserved Total Application Works


  • If you like this tutorial, tell a friend about this site (copy and paste the following link.)
    <html>
    <title>Example of a link </title>
    <body>
    <table border>
    <a href="http://sumtotalz.com/TotalAppsWorks/Client_Server/Sockets_Tutorial_III.html"> Client/Servers - An AddressBook Exaample III </a>
    </table>
    </body>
    </html>
    Download source and tutorial
    Screenshot
    Feedback
    1. 1/16/2004 5:04:51 AM: buzz: nicely done!
    2. 3/1/2005 9:05:22 PM: Hey! man! thnx for sharing your knowledge!,its great!.
    3. 1/19/2006 1:37:26 AM: ramdhani: it very good source code (,")
    4. 5/7/2007 8:25:11 AM: sudheer: this is very nice example for client server
  1. Java Table of contents
  2. 2nd Java Cup
  3. Pie Chart I
  4. Pie/Bar Chart IB
  5. Pie/Bar Chart II
  6. Pie/Bar Chart III
  7. A Basic Calculator
  8. Linked Lists
  9. Linked List II
  10. Linked List III
  11. Linked List IV
  12. Hardware Store I
  13. Hardware Store II
  14. Hardware Store III
  15. Client/Server
  16. Client/Server II
  17. Client/Server III
  18. Client/Server IV
  19. Multithreaded Client/Server
  20. Multithreaded Client/Server II
  21. Multithreaded Client/Server III
  22. Basic Calculator II
  23. Basic Calculator III
  • 1 Introduction
  • 2 Requirements
  • 3 Template Structure
  • 4 Proposed Structure
  • 5 Sockets
  • 6 What is the purpose of the setup() method?
  • 7 How do we create a simple server?
  • 8 How do we create a client?
  • 9 Process the input and output streams
  • 10 How do we put it together to build a Record Class?
  • 11 How do we put it together to build a server?
  • 12 How do we put it together to build a Client?
  • 13 Glossary

    1 Introduction

    In this tutorial, we will extend our basic client/server address application II using sockets. This tutorial assumes that you have read and completed the following tutorials.

    1. Your First Cup of Java (Sun.com site)
    2. Getting Started (Sun.com site)
    3. How to get user input and do some simple mathematical processing on the data (my site)
    4. A basic Client Server Address application
    5. A basic Client Server Address application II

    Why should client/server applications using sockets be of interest to us? If you use a browser to surf the Net, then you are using a client-server model with sockets to obtain information. This tutorial will not delve into an application as complex as a browser; however, it should serve to provide insights into how to build a basic two-tier client/server application. Our two-tier application model will look like:

    Basic two-tier application model
      
                                +------+
                                |TCP/IP|
                                +---+--+
                                    |
      Client                 +---+  |  +---+     Server
                             | S |  |  | S |
     +-------------------+   | o |  |  | o |    +-------------+
     |      GUI          |<->| c |  |  | c |<-->|             |
     +-------------------+   | k |  v  | k |    +-------------+   Address.dat
                             | e |<--->| e |                      +---------+
                             | t |     | t |     Record         +-|         |
                             +---+     +---+    +-------------+ | +----+----+
                                                |   Read      |<+      ^
                                                +-------------+        |
                                                |   Write     |--------+    
                                                +-------------+
     


    We will use TCP/IP as our Internet protocol. The Java classes that we will use will hide the TCP/IP complexities from us.

    When running this application, start the server first and then start the client.

    1. Click on Compile_C_S_III.bat
    2. Click on Start_Server.bat
    3. Click on Start_Client.bat

    In this example, we will build on the A Basic Client Server Address Application II. We will expand on the protocol we introduced in the previous example to allow adding and deleting capabilities.

    2 Requirements

    The requirements for this basic client/server application using sockets are:

    1. Build a client/server application, using the application template.
      • Use the application template to build the client.
      • Use the application template to build the server.
    2. The client application should use the following:
      • JLabel
      • JTextField
      • JButton
      • JPanel
      • JTextArea
      • JTable
      • Layout Managers
      • Dialog
    3. The server application should use the following:
      • JButton
      • JPanel
      • JTextArea
      • RandomAccessFile
      • Layout Managers
    4. Use sockets to allow two computers to communicate with each other.
      • Use the ServerSocket class for the server.
      • Use the Socket class for the client.
    5. Create a hard coded array that contains address information for initialization of a file.
    6. After initialization, the file will be used for persistent data.
    7. Develop a protocol that will be used between the client and server.
      • Use the StringTokenizer - class java.util.StringTokenizer.
      • The string tokenizer class allows an application to break (parse) a string into tokens.
      • The following actions: List; Add; Update; and Delete can be sent from the client based on the buttons at the bottom of the frame.

        Refresh Status Add Update Delete Exit

    8. Use a class that extends WindowAdapter to respond to the closing of the JFrame.
    9. Add the following classes:
      1. DeleteRec extends Dialog implements ActionListener
        • Gathers the record ID of the record to be deleted.
      2. NewRec extends Dialog implements ActionListener
        • Gathers address information for the record to be added.
      3. StatusDisp extends Dialog implements ActionListener
        • Show the communications sent to the server.
      4. UpdateRec extends Dialog implements ActionListener
        • Gathers address information for the record to be updated.
      5. Record
        • Reads and Writes address information to a file.
    A more advanced client-server application can be found at A CS Hardware Store III

    3 Template Structure

    We are going modify the template used in the Second Cup of Coffee by having it extend the JFrame class.

    Basic Client Template
      
    /** 
     * The tcpClient class implements an application and extends JFrame.
     */
    class tcpClient extends JFrame implements  ActionListener {
    
        /** tcpClient constructor */
        public tcpClient() {
           initialization code
           ...
        } 
    
        public run() { 
           // Create socket, input and output streams 
           ...
        } 
    
        public sendData() {  
           ...
        } 
    
        public static void main(String[] args) {
            tcpClient app = new tcpClient() ; /** creates an instance of tcpClient  */
        }
    }
      
    and

    Basic Server Template
      
    /** 
     * The tcpServer class implements an application and extends JFrame.
     */
    class tcpServer extends JFrame implements  ActionListener {
    
        /** tcpServer constructor */
        public tcpServer() {
           initialization code
           ...
        } 
    
        public run() { 
           // Create socket, input and output streams 
           ...
        } 
    
        public sendData() {  
           ...
        } 
    
        public static void main(String[] args) {
            tcpServer app = new tcpServer() ; /** creates an instance of tcpServer  */
        }
    }
    
      

    4 Proposed Structure

    The proposed Hardware Store Application client-server structure will look like:

    Two-Tier Basic Client/Server Hardware Store Application Structure
      
                                +------+
                                |TCP/IP|
                                +---+--+
                                    |
      tcpClient              +---+  |  +---+     tcpServer
      Methods                | S |  |  | S |     Methods
     +-------------------+   | o |  |  | o |    +-------------------+ 
     | tcpClient()       |<->| c |  |  | c |<-->| tcpServer()       |
     +-------------------+   | k |  v  | k |    +-------------------+ 
     | setUp()           |   | e |<--->| e |    | setup()           | 
     +-------------------+   | t |     | t |    +-------------------+ 
     | connect()         |   +---+     +---+    | run()             | 
     +-------------------+                      +-------------------+   
     | run()             |                      | closeConnection() | 
     +-------------------+                      +-------------------+ 
     | closeConnection() |                      | listName()        |--+ 
     +-------------------+                      +-------------------+  |
     |sendData(String )  |                      | addName()         |--+
     +-------------------+                      +-------------------+  |
     | showName()        |                      | updateName()      |--+
     +-------------------+                      +-------------------+  |
     | main()            |                      | deleteName()      |--+
     +-------------------+                      +-------------------+  |
                                                |sendData(String )  |  |
                                                +-------------------+  |
                                                | main()            |  |
                                                +-------------------+  |
                                                                       |
                                                +-------------------+  |
                                                | Record()          |<-+
                                                +------+------------+
                                              write()->|      ^     
                                                       V      |<--read()
                                                +-------------+-----+
                                 address.dat -->| Persistent Data   |
                                                +-------------------+ 
      

    The Client Methods perform the following functions:

    Client Methods Summary
    Method Description
    tcpClient() this is the class constructor used for initialization.
    setUp() this method is used to setup and allocate the GUI objects.
    connect() this method is used to connect to the socket.
    run() this method is used to create input/output streams and to listen for input from the socket.
    closeConnection() is used to close the socket connection and the input/output streams.
    sendData(String ) is used to send data to the server.
    main() this is the entry point for the client application.


    The Server Methods perform the following functions:

    Server Methods Summary
    Method Description
    tcpServer() this is the class constructor used for initialization.
    setUp() this method is used to setup and allocate the GUI objects.
    run() this method is used to create the server socket, input/output streams and to listen for input from the socket.
    closeConnection() is used to close the socket connection and the input/output streams.
    findName() this method is a stub in this version.
    addName() this method adds a name using the RandomAccessFile API and the record ID.
    updateName() this method updates a name using the RandomAccessFile API and the record ID.
    deleteName() this method will use the record ID, using the RandomAccessFile API to delete a record in the file.
    sendData(String ) is used to send data to the client.
    main() this is the entry point for the server application.


    5 Sockets

    We need a way for the Client to communicate with the Server. We will use sockets. When people are separated by distance, they communicate using telephones. If we say that their brains are a computer, then they are hooking up their brains to a telephone to communicate. Similarly, we can hook up computers using software objects so that the computers can communicate with each other. The picture for such a setup looks like:

    Sockets used to Connect PCs
     
                      TCP/IP   
                        | 
      Tier 1     +---+  |  +---+     Tier 2         
    +--------+   | S |  v  | S |   +--------+     
    | Client |<->| o |<--->| o |<->| Server |
    +--------+   | c |     | c |   +--------+     
       GUI       | k |     | k |      
                 | e |     | e |
                 | t |     | t |
                 +---+     +---+        
      
    Two PCs communicating via TCIP

    6 What is the purpose of the setup() method?

    The purpose of the setup() method is to create the JTable that is displayed on the main frame. The setup()uses the pData array which contains the data to be loaded into the JTable, and and the variable columnNames contains the column names for the JTable. The setUp() method's logic look like:

    1. Creates JButtons
    2. Creates JPanels
    3. Creates JLabels
    4. Adds Action Listeners to the JButtons
    5. Creates a JTable
    6. Adds a ScrollPane to the JTable
    7. Adds the ScrollPane to the context of the JFrame
    8. Sets the size for the JFrame
    9. Sets the location for the JFrame
    10. Makes the JFrame visible
    The above logic takes place in the setup() method. Some of you might prefer further step-wise refinement. If so, the outline might look like:

    setup() method
      
    private void setUp() {
       SetUPButtons() ;
       SetUPPanels() ;
       SetUPLabels() ;
       SetUPAddAct() ;
       SetUPTable ;
       SetUPSizePosit ;
    
    }
    private void SetUPButtons() {
       ...
    }
    private void SetUPPanels()  {
       ...
    }
    private void SetUPLabels()  {
       ...
    }
    SetUPAddAct()   {
       ...
    }
    private void SetUPTable  {
       ...
    }
    private void SetUPSizePosit {
       ...
    }
      


    This process was/is known as top-down structured programming. What I have done is take a unit (setup() method), 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; the same value that the dime has. Some of you might also prefer this granularity because in future versions of this tutorial, I remove the SetUPButtons() method and replace it with the SetUPMenu() method. Even though I do this replacement in the context of the original Setup() method, this finer granularity makes it easier to see what I have done. In object-oriented programming, programming revolves around the data. So in this style, the top is the data. It might be depicted as follows:

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

    When you consider my tutorial on How to get user input and do some simple mathematical processing on the data (my site), I introduce the concept of a template for a Java application and one for an applet. A like the concept of a template/pattern to be used as a starting point as an outline for commonly occurring problems. A design template/pattern is an outline. It is not a finished design, but it can be fleshed-out into code; it is a description or template for how to solve a problem that can be used in many different situations. For example, I can use the following generic application template/pattern as a starting for a more complex application.

    Generic application template/pattern
      
    /** 
     * The MyApp class implements an application.
     */
    class MyApp {
        private data-type dt;
          ...
    
        // MyApp constructor
        public MyApp() {
           //initialization code
           //...
        } 
    
        public static void main(String[] args) {
            MyApp app = new MyApp()  ; 
            //minimal code
            //...
        }
    } 
      


    Once the data has been defined, in the above template, I can begin my top-down structured design. Similarly, I can use the same approach to start my design effort for an applet. The template/pattern for an applet looks like:

    Generic application template/pattern
    Start top-down structured design
      
      
    import java.applet.*;
    import java.awt.*;
     
    /**
     * The MyApplet class implements an applet.
     */
    public class MyApplet extends Applet {
        
        private data-type dt;
          ...
    
        public void init() {
            // initialization code
            initialization code...
            ...
        }
    
        public void paint(Graphics g) {
            // Display "something!"
            g.drawString("something!", 50, 25);
        }
    }
      


    From Webopedia, "Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved."

    7 How do we create a simple server?

    How do we create a Server in Java? We can create a simple server if we do the following:

    1. Create a ServerSocket object.
        
       server_socket = new ServerSocket( 5050, 100,
                                        InetAddress.getByName("127.0.0.1")); 
      
         Creates a server socket and binds it to the specified local port number.
        
    2. Set up a connection and wait for the Client to connect.
        
       Socket socket = server_socket.accept(); 
      
         This class implements client sockets (also called just "sockets"). 
         A socket is an endpoint for communication between two machines. 
        
    3. Create input and output streams.
       
      BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      
         Read text from a character-input stream, buffering 
         characters so as to provide for the efficient reading of 
         characters, arrays, and lines. 
      
      PrintWriter output = new PrintWriter(socket.getOutputStream(),true);
      
         Create a new PrintWriter, without automatic line flushing, 
         from an existing OutputStream. This convenience constructor 
         creates the necessary intermediate OutputStreamWriter, which 
         will convert characters into bytes using the default 
         character encoding.
        
    4. Process the input and output streams.
    5. Close the socket and input/output streams.

    8 Process the input and output streams

    The code for processing the input and output streams is similar in both the client and server. In the following code segment, the client will listen to the socket and break the loop if the server sends the message FROM SERVER==> QUIT.

    Loop set up to listen for messages
      
    while(true) {
       String message = input.readLine();
       // stop if input line equals "QUIT"
       while ( !message.toUpperCase().equals( "FROM SERVER==> QUIT" ) ) {
          message = input.readLine();
       }
    }
      


    Where input.readLine() reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

    The following server code parses the data read from the socket. In some cases, multiple lines packed in a buffer may be sent at once. However, in this case, there is only one line sent.

    Loop set up to listen for messages
      
    
    1. while( !message.toUpperCase().equals( "QUIT" )) {
    2. message = (String)input.readLine();
    3. tokens = new StringTokenizer( message ) ;
    4. if ( tokens.countTokens() >= 1 ) {
    5. int ii = 0 ;
    6. while( tokens.hasMoreTokens() ) {
    7. messageTokens[ ii ] = tokens.nextToken().toString() ;
    8. display.append("\n" + messageTokens[ ii ] ) ;
    9. ii++ ;
    10. }
    11. display.append("\nThe value of messageTokens[ 0 ] is " + messageTokens[ 0 ] + "\n") ;
    12. if ( messageTokens[ 0 ].toUpperCase().equals( "FIND" ) ) {
    13. ; //findName() ;
    14. }
    15. else if ( messageTokens[ 0 ].toUpperCase().equals( "LISTALL" ) ) {
    16. display.append( "\nCurrrently in run() method and if LISTALL construct." ) ;
    17. listNames() ;
    18. }
    19. else if ( messageTokens[ 0 ].toUpperCase().equals( "ADD;;" ) ) {
    20. display.append( "\nCurrrently in run() method and if add construct." ) ;
    21. addName( message ) ;
    22. }
    23. else if ( messageTokens[ 0 ].toUpperCase().equals( "UPDATE;;" ) ) {
    24. display.append( "\nCurrrently in run() method and if update construct." ) ;
    25. updateName( message ) ;
    26. }
    27. else if ( messageTokens[ 0 ].toUpperCase().equals( "DELETE;;" ) ) {
    28. display.append( "\nCurrrently in run() method and if delete construct." ) ;
    29. deleteName() ;
    30. }
    31. ii = 0 ;
    32. }
    33. else {
    34. display.append( message );
    35. message = null; //so the loop will terminate the server
    36. break;
    37. } /** End of if-else */
    38. } /** End of while */


    In lines 7 through 11, we will load each set of characters, which are separated by a semicolon, into an string array (messageTokens[ ii ]). The following are the four possible responses from the server:

    1. Line 14: FIND - has no effect.
    2. Line 17: LISTALL - will cause the entire file to be read and the contents sent to the client.
    3. Line 21: ADD;; - will cause the record sent by the client to be added to the file.
    4. Line 25: UPDATE;; - will cause the record sent by the client to be updated in the file.
    5. Line 29: DELETE;; - will cause the record sent by the client to be deleted from the file.

    The above code uses the StringTokenizer class to parse the data sent from the client. Based on the first set of characters (the action), the server takes the appropriate response. Let's look at the code in more detail below.
         
      
    1. message = (String)input.readLine();
    2. tokens = new StringTokenizer( message, ";;" ) ;
    3. if ( tokens.countTokens() >= 1 ) {
    4. int ii = 0 ;
    5. while( tokens.hasMoreTokens() ) {
    6. messageTokens[ ii ] = tokens.nextToken().toString() ;
    7. display.append("\n" + messageTokens[ ii ] ) ;
    8. ii++ ;
    9. }
    10. ...
    11. }

    In the above code segment:
    • Line 1 reads data sent over the connection and stores that data in the String variable message.
    • Line 2 creates a new instance of StringTokenizer. We are using StringTokenizer to parse the String variable message.
      • class StringTokenizer extends Object implements Enumeration
        • The string tokenizer class allows an application to break a string into tokens. This means if we don't tell the StringTokenizer class where to perform the token breaks, Java will create a token of the characters encountered before a blank space. The next token will be the set of the characters encountered before the next blank space.
        • Java allows us to specify where we want the breaks to be. We do that by specifying a delimiter. In this case, our delimeter is ;;. This means that all characters encountered before ;; will be a token. For example,
             
          123 Main St.;;
            
          is a token that ends with St..
    • Line 4 checks for tokens in the data stream.
    • Lines 6 - 10 stores the tokens in a String array messageTokens.
    The first token (messageTokens[0]) tells the program what action to perform e.g., List, Add, Update, or Delete.

    9 How do we create a client?

    How do we create a client GUI in Java?

    Loop set up to listen for messages
       
      
    1. Create the JButtons. status = new JButton( "Status" ); refresh = new JButton( "Refresh" ); add = new JButton( "Add" ); update = new JButton( "Update" ); delete = new JButton( "Delete" ); exit = new JButton( "Exit" );
    2. Create the JPanel. buttonPanel = new JPanel() ;
    3. Add the buttons to the JPanel. buttonPanel.add( refresh ) ; buttonPanel.add( status ) ; buttonPanel.add( add ) ; buttonPanel.add( update ) ; buttonPanel.add( delete ) ; buttonPanel.add( exit ) ;
    4. Add the JPanel to the bottom (SOUTH) of the content pane container. c.add( buttonPanel , BorderLayout.SOUTH) ;
    5. Create status dialog box statusDisp = new StatusDisp ( tcpC ) ;
    6. Create the List using JTable listPanel = new JPanel(); listPanel.setLayout( borderManager ); table = new JTable( pData, columnNames ); table.setEnabled( false ); scrollpane = JTable.createScrollPaneForTable( table ) ;
    7. Add the JTable to the content pane. c.add( scrollpane )


    JTable is a user-interface component that allows the programmer to present data in a tabular or two-dimensional table format.

    • JTable(Object[][] rowData, Object[] columnNames)
      • Constructs a JTable to display the values in the two dimensional array, rowData, with column names, columnNames.
      • For example,
         
        table = new JTable( pData, columnNames );
          

    How do we create a client socket in Java?

    1. Create a Socket to make connection on port 5050 and host name "127.0.0.1".
       
      Socket client = new Socket(
             InetAddress.getByName( "localhost" ), 5050 );
        
    2. Get the Object input and output streams.
       
      BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      PrintWriter output = new PrintWriter(socket.getOutputStream(),true);
        
    3. Listen on the connection and process the I/O.
    4. Close the connection, input and output streams.

    10 How do we put it together to build a Record Class?

    The Record Class defines the address record and allows the user to read and/or write to the address.dat file. An outline of the Record Class looks like:

    Building a Record Class
      
    public class Record  {
    
       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 static int getSize() { return 752; }
    }
      


    The method summary looks like:

    Record Class Method Summary
    Method Description
    fill() The fill method is used to fill in the passed string with blanks.
    getAddress() The getAddress() method is used to obtain and return the Address.
    getCity() The getCity() method is used to obtain and return the City.
    getEmail() The getEmail() method is used to obtain and return the Email.
    getFirstName() The getFirstName() method is used to obtain and return the First Name.
    getLastName() The getLastName() method is used to obtain and return the Last Name.
    getRecID() The getRecID() method is used to obtain and return the record ID.
    getSize() NOTE: This method contains a hard coded value for the size of a record of information
    getState() The getState() method is used to obtain and return the State.
    getTelephone() The getTelephone() method is used to obtain and return the Telephone.
    getZip() The getZip() method is used to obtain and return the Zip.
    ReadRec() ReadRec() reads a record from the specified RandomAccessFile.
    setAddress() The setAddress() method is used to set the Address field in this record.
    setCity() The setCity() method is used to set the City field in this record.
    setEmail() The setEmail() method is used to set the tEmail field in this record.
    setFirstName() The setFirstName() method is used to set the First Name field in this record.
    setLastName() The setLastName() method is used to set the Last Name field in this record.
    setRecID() The setRecID() method is used to set the RecID field in this record.
    setState() The setState() method is used to set the State field in this record.
    etTelephone(java.lang.String f) The setTelephone() method is used to set the Telephone field in this record.
    setZip() The setZip() method is used to set the Zip field in this record.
    write(java.io.RandomAccessFile file) Write a record to the specified RandomAccessFile file

    11 How do we put it together to build a server?

    The outline for the server is shown below.



    tcpServer Class
     
    /** **************************************************************
     * tcpServer.java
     ****************************************************************/
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import Record;
    
    public class tcpServer extends JFrame implements  ActionListener {
        
    
        public  tcpServer() {
           super ( "Server" ) ;
    
           setup() ;
    
           run() ;
        }
    
        public  void setup() {
          
        }
    
        public void InitRecord() {
          
        }
    
        public void run() {
           
        }
    
       /**
        * This method responds to the send, cancel or exit button
        *  being pressed on the tcpClient frame.
        */
       public void actionPerformed( ActionEvent e )    {
          
       }
    
       private void closeConnection() {
          
       }
    
       public void addName( String message ) {
    
           
       }
    
       public void listNames() {      
    
    
       }
    
       public void updateName( String message ) {       
    
    
       }
    
       public void deleteName() {
           
       }
    
      /** Send the found record back to the client */
       private void sendData(String str) {
    
       }
    
        public static void main(String args[]) {
           final tcpServer server = new tcpServer() ;
           server.addWindowListener(
             new WindowAdapter() {
                public void windowClosing( WindowEvent e )
                {
                   server.closeConnection() ;
                   System.exit( 0 );
                }
             }
          );
        }
    
    
       class WindowHandler extends WindowAdapter {
          
       }
    
    }
    
    
      


    tcpServer Class Method Summary
    Method Description
    actionPerformed() The actionPerformed() method responds to the send, cancel or exit button being pressed on the tcpClient frame.
    addName() The addName() this method adds a name using the RandomAccessFile API and the record ID.
    deleteName() The method deleteName() will use the record ID and the RandomAccessFile API to delete a record in the file.
    InitRecord() The InitRecord() method is called to initialize the address.dat file,
    listNames() The listNames() method is used to gather all of the records in the address.dat file and send this data back to the client.
    main(java.lang.String[] args) The main() method is the entry point the Java calls when for the server application is loaded into memory.
    run() The run() method is used to create the server socket, input/output streams and to listen for input from the socket.
    setup() this method is used to setup and allocate the GUI objects.
    updateName() The updateName() method updates a name using the RandomAccessFile API and the record ID.

    12 How do we put it together to build a Client?

    In addition to the tcpclient class, there are nested classes that exist for the purpose of

    1. Adding new records;
    2. Updating records;
    3. Deleting records;
    4. Responding to the request to shut down the Client;
    5. Showing diagnostic messages;


    Nested Class Summary
    Class Description
    DeleteRec The DeleteRec class is used to create the Delete Record dialog, which in turn, is used to to delete records from the specified table(s).
    NewRec The NewRec class is used to gather and insert data for new address records.
    StatusDisp The StatusDisp class shows the log of the Client's printed diagnostics.
    UpdateRec The purpose of the UpdateRec class is used to update an address record.
    WindowHandler WindowHandlerThe WindowHandler class is called to help shut down the Client.

    The outline for the Client is shown below.



    tcpClient Class
     
    /*************************************************************
     * tcpClient.java
     * 
     *************************************************************/
    
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.awt.event.*;
    import java.util.*;
    import java.net.*;
    
    public class tcpClient extends JFrame implements  ActionListener {
    
       public tcpClient() {
          super( "Client" ) ;
    
          setUp() ;
    
          connect() ;
    
          run() ;
    
          closeConnection() ;
       }
    
       /** The setUp() method does the intialization for the application */
       private void setUp() {
    
          
          /** Create dialog boxes */
    
          statusDisp  = new StatusDisp ( tcpC  ) ;
    
          /** set up the List */
          listPanel = new JPanel();
          listPanel.setLayout( borderManager );
          table = new JTable( pData, columnNames );
          table.setEnabled( false );
          scrollpane = JTable.createScrollPaneForTable( table ) ;
          c.add( scrollpane ) ;
    
          addWindowListener( new WindowHandler( this ) );
          setSize( 500, 400 );
          setLocation( 450, 20 ) ;
          show();
    
       }
    
    /** The connect() method does the intialization of the client socket
     *  on localhost and port 5050*/
       private void connect() {
          // connect to server      
       }
    
       private void sendData(String str) {
          output.println( str );
       }
    
       public void sysPrint( String str  )   {
          if ( myDebug ) {
             System.out.println( str );
          }
       }
    
       public String[][] getPData() {
          return pData ;
       }
    
       public int getEntries(  )   {
          return numEntries  ;
       }
    
       public void setEntries( int ent )   {
          numEntries = ent ;
       }
    
       public int getNumEntries() {
          return numEntries ;
       }
    
       private void run() {
          
       }
    
       /**
        * This method responds to the find, delete, clear or exit button
        *  being pressed on the tcpClient frame.
        */
       public void actionPerformed( ActionEvent e )    {
    
          if ( e.getSource() == exit ) {
                closeConnection() ;
          }
          // list all names in the array
          else if ( e.getSource() == refresh ) {
             table = new JTable( pData, columnNames );
             table.repaint();
          }
          else  if ( e.getSource() == clear ) {
             enterBox.setText( "" );
          }
          // show the communications and actions
          else if ( e.getSource() == status ) {
                statusDisp.setVisible( true );
          }
          else if ( e.getSource() == add ) {
             newRec      = new NewRec( tcpC,  table, pData );
             newRec.setVisible( true );
          }
          else if ( e.getSource() == update ) {
                updateRec   = new UpdateRec( tcpC,  pData, iii );
          }
          else if ( e.getSource() == delete ) {
             deleteRec   = new DeleteRec( tcpC,  table, pData );
             deleteRec.show( true );
          }
       }
    /** Left over from the previous version - does nothing stub */
       private void showName() {
          
       }
    
       private void listNames() {
          if ( !messageTokens[ 1 ].equals( "" ) && !messageTokens[ 1 ].equals( " " )) {
             statusDisp.display.append( "\n Last Name: " + messageTokens[ 1 ]  ) ;
          }
       }
    
       private void listAllNames() {
    
       }
    
       private void closeConnection() {
          
       }
    
       public static void main(String[] args) {
          final tcpClient client = new tcpClient() ;
    
          client.tcpC = client ;
    
          client.addWindowListener(
             new WindowAdapter() {
                public void windowClosing( WindowEvent e )
                {
                   client.closeConnection() ;
                }
             }
          );
       }
    
       class WindowHandler extends WindowAdapter {
          tcpClient tcpC;
    
          public WindowHandler( tcpClient t ) { tcpC = t; }
    
          public void windowClosing( WindowEvent e ) { tcpC.closeConnection(); }
       }
    
    
    class StatusDisp extends Dialog
             implements ActionListener {
    
       private JButton exit ;
       //private Record data;
       private int theRecID, ii;
       private String pData [] [] ;
       private tcpClient tclient ;
       JTextArea display ;
    
       public StatusDisp(  tcpClient t_client  )     {
    
          /** setup() creates the JLablels, JButtons, and JTextFields */
          setup() ;
       }
    
       public void setup() {
    
       }
    
       public void actionPerformed( ActionEvent e )   {
    
          if ( e.getSource() == exit ) {
             setVisible( false );
             clear();
          }
       }
    
       private void clear()
       {
    
       }
    }
    
    
    class UpdateRec extends Dialog
             implements ActionListener {
       
    
       public UpdateRec(  tcpClient t_client,
                          String p_Data [] [], int iiPassed)     {
    
          super( new Frame(), "Update Record", true );
    
          /** setup() creates the JLablels, JButtons, and JTextFields */
          setup() ;
    
       }
    
       public void setup() {
    
       }
    
       public void actionPerformed( ActionEvent e )   {
    
       }
    
       private void clear()
       {
          
       }
    }
    
    
    
    class NewRec extends Dialog
            implements ActionListener {
    
    
       public NewRec( tcpClient t_client, JTable tab,
                            String p_Data[] []  )
       {
          super( new Frame(), "New Record", true );
    
          setup() ;
       }
    
       public void  setup() {
    
       }
    
       public void actionPerformed( ActionEvent e )
       {
    
          
       }
    
       private void clear()
       {
       }
    }
    
    
    class DeleteRec extends Dialog
              implements ActionListener {
    
       public DeleteRec( tcpClient t_client ,
                       JTable tab, String p_Data[] []  )
       {
         
       }
    
       public void actionPerformed( ActionEvent e )
       {
          
       }
    
       private void clear()   {
    
       }
    }
     




    tcpClient Class Method Summary
    Method Description
    actionPerformed() This method responds to the refresh, status, add, update, delete or exit buttons being pressed on the tcpClient main frame.
    getEntries() The getEntries() method returns the number of entries in the array.
    getNumEntries() The getNumEntries() method returns the number of entries in the array.
    getPData() The pData() method returns a reference to the pData array.
    main() The main() method is the entry point called by Java when this application is loaded.
    setEntries() The setEntries() method sets the number of entries in the array.
    sysPrint() The sysPrint() method prints diagnostic data for debugging the application.

    13 Glossary

    Client-Server - A client is a requester of services and a server is the provider of services.

    extends - when considering class MyClass extends ParentClass, MyClass inherits from ParentClass. Java does not support multiple inheritance; it supports only single inheritance.

    Inheritance - when a class is defined, any subclass that is defined can inherit the definitions (public and/or protected) of the parent/base classes.

    JFrame - A JFrame is a top-level window with a title and a border.

    protocol - this is the format that we will use to communicate between the client and the server.

    Requirement - In this instance, a specification that documents the functions, performance, design constraints and attributes of a program to be delivered.

    Socket - a software object that connects an application to a network protocol. In Java, a program can send and receive TCP/IP messages by opening a socket and reading and writing data to and from the socket.

    Template - is a unique class or pattern that can be used to build other software code.

    Two-tier - A client/server architectures where the GUI runs on the client and the random access file is stored on the server.
    tcpClient Class
    
      Tier 1        Tier 2         
    +--------+     +--------+     
    | Client |<--->| Server |
    +--------+     +--------+     
       GUI                
                     
     

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

    Process -An executing program.

    Sockets - a software object that connects an application to a network protocol, such as TCP/IP.

    TCP/IP - is an abbreviation for Transmission Control Protocol/Internet Protocol, the suite of communications protocols, which are used to connect hosts over the Internet.

    Template - is a unique class or pattern that can be used to build other software code.






















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

    © 2002 - 2011 All Rights Reserved Total Application Works