Tutorial: Basic Client/Server Application IV


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 it (copy and paste the following URL or send this page to a friend.)
    <html>
    <title>Example of a link </title>
    <body>
    <table border>
    <a href="http://sumtotalz.com/TotalAppsWorks/Client_Server/Sockets_Tutorial_IV.html"> Client/Servers - An AddressBook Exaample IV </a>
    </table>
    </body>
    </html>
  • On-site classes can be arranged in Java and C++. Send all inquiries to:
    RonHolland@sumtotalz
    Feedback
    1. 5/25/2004 8:16:04 PM: Don Roberts: Excellent post. Can't wait to read it in more detail to see how it works.
    2. 8/16/2004 2:43:55 PM: Good Program, nice server code
  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
  • Introduction
  • Requirements
  • Registering Addressbook1 as an ODBC Data Source
  • Proposed Structure
  • Sockets
  • How do we create a simple server?
  • Converting to SQL
  • How do we create a client?
  • Process the input and output streams
  • How do we put it together to build a server?
  • How do we put it together to build a Client?
  • Definitions

    Introduction

    In this tutorial, we will extend our basic client/server application III 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. Click on Complete Applications and download A basic Client Server application
    5. Click on Complete Applications and download A basic Client Server application II
    6. Click on Complete Applications and download A basic Client Server application III

    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 three-tier client/server application. In the previous examples, our two-tier application model looked like:

    
                                +------+
                                |TCP/IP|
                                +---+--+
                                    |
      Client                 +---+  |  +---+     Server
                             | S |  |  | S |
     +-------------------+   | o |  |  | o |    +-------------+
     |                   |<->| c |  |  | c |<-->|             |
     +-------------------+   | k |  v  | k |    +-------------+
                             | e |<--->| e |      
                             | t |     | t |     
                             +---+     +---+
     
    Figure 1: Two-tier application model


    In this example, our application model will look like:

    
                                +------+
                                |TCP/IP|
                                +---+--+
                                    |
      Client                 +---+  |  +---+     Server
                             | S |  |  | S |
     +-------------------+   | o |  |  | o |    +-------------+
     |                   |<->| c |  |  | c |<-->|             |
     +-------------------+   | k |  v  | k |    +------^------+
                             | e |<--->| e |           |      
                             | t |     | t |           |    
                             +---+     +---+       +---v----+
                                                   | RDBMS  |
                                                   +--------+
     

    Figure 2: Updated two-tier application model


    This tutorial will change our basic architecture from a two-tier to a three-tier architecture. Specifically, we will replace the Record class with an interface to the Microsoft Access database. 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 Application III. We will expand on the protocol we introduced in the previous example to use the SQL interface to access the database.

    Requirements

    The requirements for the previous basic client/server application using sockets were:

    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.
    10. (NEW REQUIREMENTS):
      • The MS Access database must be installed on the computer.
      • Register AddressBook1 as an ODBC Data Source.
      • Replace the Record class with the MS Access relational database.
    A more advanced client-server application can be found at Click on Complete Applications and download A CS Hardware Store III

    Registering Addressbook1 as an ODBC Data Source

    The AddressBook1.mdb database file shipped with this example is needed to run the Basic Client/Server Application IV example and it must be registered as ODBC sources in Windows. The following steps register an .mdb data file in a Windows 98/XP system.

    1. Open your Control Panel and double-click on the ODBC Data Sources icon. The ODBC Data Source Administrator dialog box will appear.
      • In Windows XP,
        1. Click on Administrative Tools
        2. Click on Data Sources (ODBC)
    2. Make sure the User DSN tab is selected.

      Figure 3: ODBC Data Source


    3. Click Add to display the Create New Data Source dialog box.
    4. Select the driver for which you want to register a data source and then click Finish.

      Figure 4: Create New Data Source


      This displays the ODBC Microsoft Access Setup dialog box.

      Figure 5: ODBC Microsoft Access Setup


    5. Click on the Select button.
    6. The Select Database dialog will appear.

      Figure 6: Select Database


      1. Go to the Drive and Folder where the AddressBook1 database is stored.
      2. Double click on AddressBook1.mdb
      3. Click on the OK button
    7. When the ODBC Microsoft Access Setup dialog appears, type in AddressBook1. (NOTE: The filetype .mdb is excluded.)

      Figure 7: ODBC Microsoft Access Setup


    8. Click OK to exit to the ODBC Data source Administrator dialog box.
    9. Click OK to exit the ODBC Data Source Administrator.

    Proposed Structure

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

     
    
                                +------+
                                |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()            |  |
                                                +-------------------+  |
                                                                       |
                                                +-------------------+  |
                                                | MS Access RDBMS   |<-+
                                                +-------------------+   
                                                                       
      
    Figure 8: Three-Tier Basic Client/Server Application Structure


    The Client Methods perform the following:

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

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


    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:

     
                      TCP/IP   
                        | 
      Tier 1     +---+  |  +---+     Tier 2         
    +--------+   | S |  v  | S |   +--------+     
    | Client |<->| o |<--->| o |<->| Server |
    +--------+   | c |     | c |   +--------+     
       GUI       | k |     | k |      
                 | e |     | e |
                 | t |     | t |
                 +---+     +---+        
      
    Figure 9: Computer Client/Server Application Structure


    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.

    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.

      
    while(true) {
       String message = input.readLine();
       // stop if input line equals "QUIT"
       while ( !message.toUpperCase().equals( "FROM SERVER==> QUIT" ) ) {
          message = input.readLine();
       }
    }
      
    Figure 10: Process the input and output streams


    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.

        
      
    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 */
    Figure 11: Process the input and output streams


    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. }
    Figure 12: Process the input and output streams


    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.

    Converting to SQL

    For the all practical purposes, the change to SQL was minimal. The Record class access was removed from the Server code. Code like:

     
    
           display.append( "\nThe size of the recID is " +
              messageTokens[ 1 ].length() );
           data.setRecID( Integer.parseInt( messageTokens[ 1 ].trim() ) ) ;
           data.setFirstName( messageTokens[ 2 ] ) ;
           data.setLastName( messageTokens[ 3 ] )  ;
           data.setAddress(  messageTokens[ 4 ] )  ;
           data.setCity( messageTokens[ 5 ] ) ;
           data.setState(  messageTokens[ 6 ] ) ;
           data.setZip(  messageTokens[ 7 ]  ) ;
           data.setTelephone( messageTokens[ 8 ] ) ;
           data.setEmail( messageTokens[ 9 ] ) ;
    
           try {
              file = new RandomAccessFile( "address.dat", "rw" );
              file.seek(  0  * data.getSize() );
              file.seek(  Integer.parseInt( messageTokens[ 1 ] ) * data.getSize() );
              data.write( file );
              file.close();
           }
           catch (IOException e) {
              display.append("\n" + e);
           }
     

    was replaced by:
      
    try {
              // creates an object that implements the Statement interface
              Statement statement = connect.createStatement();
    
              if ( tokens.countTokens() >= 1 )   {
    
                 while( tokens.hasMoreTokens() )  {
                    messageTokens[ ii ] = tokens.nextToken().trim().toString() ;
                    display.append("\n" + messageTokens[ ii ] ) ;
                    ii++ ;
                 }
              }
    
              display.append( "\nThe size of the recID is " +
                 messageTokens[ 1 ].length() );
              String query = "INSERT INTO Addresses (" +
                                  "firstname, lastname, address, city, " +
                                  "stateorprovince, postalcode, country, " +
                                  "emailaddress, homephone, faxnumber" +
                                  ") VALUES ('" +
                                  messageTokens[ 1 ] + "', '" +
                                  messageTokens[ 2 ] + "', '" +
                                  messageTokens[ 3 ] + "', '" +
                                  messageTokens[ 4 ] + "', '" +
                                  messageTokens[ 5 ] + "', '" +
                                  messageTokens[ 6 ] + "', '" +
                                  messageTokens[ 7 ] + "', '" +
                                  messageTokens[ 8 ] + "', '" +
                                  messageTokens[ 9 ] + "', '" +
                                  messageTokens[ 10 ] + "')";
    
              int result = statement.executeUpdate( query );
              if ( result == 1 )
                      display.append("\nThe record was successful in addName()." ) ;
    
              statement.close();
           }
           catch ( SQLException sqlex ) {
                sqlex.printStackTrace();
                display.append( sqlex.toString() );
           }
    
      

    Figure 13: Change to SQL


    Where

    1. Statement statement
      • The object used for executing a static SQL statement and obtaining the results produced by it.
    2. executeQuery(String sql)
      • Executes a SQL statement that returns a single ResultSet.
    3. String query
      • Contains the SQL query statement.
    This new code adds a record to the AddressBook1 database.

    The following code updates a record in the AddressBook1 database.

      
    String query = "UPDATE addresses SET " +
                       "firstname='" + messageTokens[ 2 ] +
                       "', lastname='" + messageTokens[ 3 ] +
                       "', address='" + messageTokens[ 4 ] +
                       "', city='" + messageTokens[ 5 ] +
                       "', stateorprovince='" + messageTokens[ 6 ] +
                       "', postalcode='" + messageTokens[ 7 ] +
                       "', country='" + messageTokens[ 8 ] +
                       "', emailaddress='" + messageTokens[ 9 ] +
                       "', homephone='" + messageTokens[ 10 ] +
                       "', faxnumber='" + messageTokens[ 11 ] +
                       "' WHERE id=" + messageTokens[ 1 ];
    
              int result = statement.executeUpdate( query );
              if ( result == 1 )
                      display.append("\nThe record was successful in updateName()." ) ;
    
      
    Figure 14: Update a record in the AddressBook1 database


    The following code deletes a record in the AddressBook1 database.

      
    String query = "DELETE FROM Addresses WHERE id="
                               + messageTokens[ 1 ];
              int result = statement.executeUpdate( query );
    
              if ( result == 1 )
                      display.append("\nThe record was successful in deleteName()." ) ;
    
      
    Figure 15: Delete a record in the AddressBook1 database


    How do we create a client?

    How do we create a client GUI in Java?

       
      
    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 )
    Figure 16: How to create a client


    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.
    Figure 17: How to create a client socket in Java


    How do we put it together to build a server?

    The outline for the server is shown below.



     
    /** **************************************************************
     * 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 {
          
       }
    
    }
    
    
      
    Figure 18: How to create a client


    How do we put it together to build a Client?

    The outline for the Client is shown below.



     
    /*************************************************************
     * 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()   {
    
       }
    }
    
    
     


    Figure 19: How do we put it together to build a Client

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

    SQL (Structured Query Language) - is the standard language used to communicate with a relational database.

    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.

    
      Tier 1        Tier 2         
    +--------+     +--------+     
    | Client |<--->| Server |
    +--------+     +--------+     
       GUI                
                     
     

    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 
     

    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