Tutorial: Basic Client/Server Application II


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






To visit my Site

To contact us

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

© 2002 - 2011 All Rights Reserved Total Application Works


  • Tell a friend about this site (copy and paste the following link 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_II.html"> Client/Servers - An AddressBook Exaample II </a>
    </table>
    </body>
    </html>
  • Download source and tutorial
  • Screenshot
    1. 12/8/2004 8:42:03 AM: good ,it's smart,come on
    2. 9/4/2005 10:19:36 PM: tanmay hi mate this is been a good job done thanks and byeee. And keep up the good work.
  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
  • What is a socket?
  • Requirements
  • Template Structure
  • Proposed Structure
  • Sockets
  • How do we create a simple server?
  • How do we create a client?
  • Process the input and output streams
  • How do we put it together to build a server?
  • How does the Server work?
  • How do we put it together to build a Client?
  • How does the Client work?

    Introduction

    In this tutorial, we will extend our basic client/server application using sockets. The intent for the overall tutorials is to build a Client/Server Address Book. This second tutorial on sockets and Client/Server technology 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 application
    In this tutorial, we will build a very simple address book.

    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:

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

    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.bat
    2. Click on Start_Server.bat
    3. Click on Start_Client.bat

    In this example, our client will request address information based on a last name. If the name exists in a hard coded array, the record information will be returned; otherwise, the response will be NOTFOUND. In addition, you will be able to delete records. I considered allowing Add and Update actions, but I felt that the logic required to perform these actions was too much of a jump for this version of the Basic Client Server Application. As we proceed with the development of this application, remember that the client makes requests of the server and the server responds to those requests.

    What is a socket?

    What is a socket? What is a corresponding analogy in humans? One method of communicating between humans is speech. Sounds emanate from the mouth and are received by the ear. Other examples are:

    1. Radio to ear
    2. Television to ear
    3. Mouth to telephone-mouth-piece to telephone-ear-piece to ear
    4. Computer to computer
    More basically, a radio station broadcasts a signal and your radio/receiver receives that broadcasted signal. A socket enables a computer to send a signal to another computer and for that other computer to receive that signal. In humans, there is a brain and a set of ears. In computers there is a processor and a port. The processor is the brain and the port is the ear. Sockets allow computers to communicate with each other. A socket is an endpoint that allows communication between two computers. You know where someone lives by their street address. With computers, you can address a computer if you know that computer's internet address (or IP address) and its port number.



    In our example, we want to set up a server that runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request. An example of how this is done follows:
      
    ServerSocket(int port, int backlog, InetAddress bindAddr)
              Create a server with the specified port, listen backlog, 
                  and local IP address to bind to.
       
    The code looks like:
      
    ServerSocket server_socket = new ServerSocket( 5050, 100,
                       InetAddress.getByName("127.0.0.1"));
       
    In this case,
    1. The port is 5050 - The port number on the remote host to which this socket is connected
    2. The backlog is 100 - The maximum queue length for incoming connection indications (a request to connect) is set to the backlog parameter.
    3. The InetAddress is "127.0.0.1" - the local IP address to bind to
    We need code that allows the Client talk to the Server, and it looks like:
      
    Socket(InetAddress address, int port)
              Creates a stream socket and connects it to the specified port 
                  number at the specified IP address.
       

    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
      • Layout Managers
    3. The server application should use the following:
      • JButton
      • JPanel
      • JTextArea
      • 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.
    6. 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 (Find and Delete) can be sent from the client based on the buttons at the bottom of the frame.

        Find Delete Clear Message Exit

    7. Use a class that extends WindowAdapter to respond to the closing of the JFrame.
    A more advanced client-server application can be found at A CS Hardware Store III

    Template Structure

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

      
    /** 
     * The tcpClient class implements an application and extends JFrame.
     */
    class tcpClient extends JFrame implements  ActionListener {
    
        /** tcpClient constructor */
        public tcpClient() {
           initialization code
           ...
        } 
    
        public static void main(String[] args) {
            tcpClient app = new tcpClient() ; /** creates an instance of tcpClient  */
        }
    }
    
    and
    /** 
     * The tcpServer class implements an application and extends JFrame.
     */
    class tcpServer extends JFrame implements  ActionListener {
    
        /** tcpServer constructor */
        public tcpServer() {
           initialization code
           ...
        } 
    
        public static void main(String[] args) {
            tcpServer app = new tcpServer() ; /** creates an instance of tcpServer  */
        }
    }
    
      

    Proposed Structure

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

     
    
    Two-Tier Basic Client/Server 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() | +---+ +---+ | RunServer() | +-------------------+ +-------------------+ | RunClient() | | closeConnection() | +-------------------+ +-------------------+ | closeConnection() | | findName() | +-------------------+ +-------------------+ |sendData(String ) | | addName() | +-------------------+ +-------------------+ | showName() | | updateName() | +-------------------+ +-------------------+ | main() | | deleteName() | +-------------------+ +-------------------+ |sendData(String ) | +-------------------+ | main() | +-------------------+

    The Client Methods perform the following:
    Method Decription
    actionPerformed() This method responds to the find, delete, clear or exit button being pressed on the tcpClient frame.
    closeConnection() This method closes the socket connect to the server.
    connect() this method is used to connect to the socket.
    listNames() This method lists all of the name found by the server.
    main() this is the entry point that Java calls when the client application is loaded.
    RunClient() this method is used to create input/output streams and to listen for input from the socket.
    sendData(String ) is used to send data to the server.
    setUp() this method is used to setup and allocate the GUI objects.
    showName() This method shows the name found by the server.
    tcpClient() this is the class constructor used for initialization.


    The Server Methods perform the following:
    Method Decription
    tcpServer() this is the class constructor used for initialization.
    setUp() this method is used to setup and allocate the GUI objects.
    RunServer() 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 will search the array and return data to client if record exists
    addName() this is a stub (no code)
    updateName() this is a stub (no code)
    deleteName() this method will search the array and delete data if record exists
    sendData(String ) is used to send data to the client.
    main() this is the entry point that Java calls when the server application is loaded.


    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 |
                 +---+     +---+        
      

    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();
       }
    }
      

    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 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. tokens = new StringTokenizer( message, ";" ) ;
    2. if ( tokens.countTokens() > 1 ) {
    3. int ii = 0 ;
    4. while( tokens.hasMoreTokens() ) {
    5. messageTokens[ ii ] = tokens.nextToken().toString() ;
    6. ii++ ;
    7. }
    8. if ( messageTokens[ 0 ].toUpperCase().equals( "RECORDFOUND" ) ) {
    9. showName() ;
    10. }
    11. else if ( messageTokens[ 0 ].toUpperCase().equals( "RECORDDELETED" ) ) {
    12. display.append( "\n" + message ) ;
    13. }
    14. else if ( messageTokens[ 0 ].toUpperCase().equals( "NOTFOUND" ) ) {
    15. display.append( "\n" + message ) ;
    16. }
    17. }
    In lines 4 through 8, we will load each set of characters, which are separated by a semicolon, into an string array (messageTokens[ ii ]). The following are the three possible responses from the server:
    1. Line 10: RECORDFOUND - the last name submitted was found by the server and the record was returned to the client.
    2. Line 13: RECORDDELETED - the last name submitted was deleted from the array.
    3. Line 16: NOTFOUND - the last name submitted was not found in the array.

    The above code uses the StringTokenizer class to parse the data sent from the server. Based on the first set of characters (the action), the client takes the appropriate response.

    How do we create a client?

    How do we create a client GUI in Java?

       
      
    1. Create the JButtons. send = new JButton( "Send" ); clear = new JButton( "Clear Message" ); exit = new JButton( "Exit" );
    2. Create the JPanel. buttonPanel = new JPanel() ;
    3. Add the buttons to the JPanel. buttonPanel.add( send ) ; buttonPanel.add( clear ) ; buttonPanel.add( exit ) ;
    4. Add the JPanel to the bottom (SOUTH) of the content pane container. c.add( buttonPanel , BorderLayout.SOUTH) ;
    5. Create a JLabel. enterLabel = new JLabel("Enter message below and then press send or clear." ) ;
    6. Create a JTextField. enterBox = new JTextField( 100 );
    7. Create the JPanel. textPanel = new JPanel() ;
    8. Set the layout manager for the JPanel. textPanel.setLayout( new GridLayout( 2, 1 ) );
    9. Add the JLabel and JTextField to the JPanel. textPanel.add( enterLabel ) ; textPanel.add( enterBox ) ;
    10. Add the JPanel to the content pane. c.add( textPanel , BorderLayout.NORTH) ;
    11. Create the JTextArea. display = new JTextArea();
    12. Add the JTextArea to the content pane. c.add( new JScrollPane( display ), BorderLayout.CENTER );

    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.

    How do we put it together to build a server?

    The outline for the server is shown below.

     
    
    
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    
    public class tcpServer extends JFrame implements  ActionListener {
        
    
        public  tcpServer() {
           super ( "Server" ) ;
    
           setup() ;
    
           RunServer() ;
        }
    
        public  void setup() {
    
        }
    
        public void RunServer() {
           
        }
    
       /**
        * This method responds to the send, cancel or exit button
        *  being pressed on the tcpClient frame.
        */
       public void actionPerformed( ActionEvent e )    {
          if ( e.getSource() == exit )
             closeConnection() ;
       }
    
       private void closeConnection() {
    
       }
    
    
        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 tcpS;
    
          public WindowHandler( tcpServer t ) { tcpS = t; }
    
          public void windowClosing( WindowEvent e ) { tcpS.closeConnection(); }
       }
    
    }
    
      

    How does the Server work?

    This is the flow when the Server is started.

    1. Java calls the Server's main method.
    2. In the Server's main method, an instance of the tcpServer class is created.
    3. The tcpServer's constructor is called.
    4. In the tcpServer's constructor,
      1. The setup method is called.
      2. The RunServer method is called.
        1. An instance of the ServerSocket class is created.
        2. An outer infinite loop is created for the purposes of listening for messages.
        3. A socket is attached to the ServerSocket and it begins listening for messages.
        4. A BufferedReader and an InputStreamReader are attached to this socket.
        5. A PrintWriter is attached to this socket for the purposes of output.
        6. An inner loop is set up to listen for messages.
        7. The BufferedReader listens on the socket in asynchronous mode.
          • This means that the BufferedReader object input is triggered when a message is received.
          • The messages that can trigger the Server's filter are:
            • FIND
            • LISTALL
            • ADD
            • UPDATE
            • DELETE
        8. When a message is received, the Server acknowledges the receipt of the message by sending a message to the Client.
        9. If a message is received that requests that the Server Quit, the Server will close it socket.

    How do we put it together to build a Client?

    The outline for the Client is shown below.

     
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.awt.event.*;
    import java.net.*;
    
    public class tcpClient extends JFrame implements  ActionListener {
       
       public tcpClient() {
          super( "Client" ) ;
    
          setUp() ;
    
          connect() ;
    
          RunClient() ;
    
          closeConnection() ;
       }
    
       /** The setUp() method does the intialization for the application */
       private void setUp() {
         
    
       }
    
    /** 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) {
          
       }
    
       private void RunClient() {
          
       }
    
       /**
        * This method responds to the send, cancel or exit button
        *  being pressed on the tcpClient frame.
        */
       public void actionPerformed( ActionEvent e )    {
          if ( e.getSource() == exit ) {
          }
          // list all names in the array
          else if ( e.getSource() == list ) {
          }
          else  if ( !enterBox.getText().equals( "" ) ) {
             if ( e.getSource() == clear ) {
             }
             // get user input and send it to server
             else if ( e.getSource() == find ) {
             }
             else if ( e.getSource() == add ) {
             }
             else if ( e.getSource() == update ) {
             }
             else if ( e.getSource() == delete ) {
             }
          }
          else {
              JOptionPane.showMessageDialog(null,
                     "Please enter a last name" + "\n",
                     "No last name",
                     JOptionPane.INFORMATION_MESSAGE ) ;
          }
       }
    
       private void closeConnection() {
          
       }
    
       public static void main(String[] args) {
          final tcpClient client = new tcpClient() ;
    
          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(); }
       }
    
    }
    
    
     

    How does the Client work?

    This is the flow when the Client is started.

    1. Java calls the Client's main method.
    2. In the Client's main method, an instance of the tcpClient class is created.
    3. The tcpClient's constructor is called.
    4. In the tcpClient's constructor,
      1. The setUp method is called. In the setUp() method:
        1. JButtons are created
        2. JPanels are created
        3. JLabels are created
        4. Action Listeners are added to the JButtons
        5. Sets the size for the JFrame
        6. Sets the location for the JFrame
        7. Makes the JFrame visible
      2. connect method is called.
        1. A Socket instance is created and connected to the specified port number (5050) at the specified IP address (localhost).
      3. RunClient method is called.
        1. A BufferedReader and an InputStreamReader object are created.
        2. An infinite loop is created to listen for messages from the Server.
        3. If a QUIT message is received from the server, the socket is closed.
      4. actionPerformed method is called asynchronously in response to the
        • List
        • Find
        • Delete
        • Clear and/or
        • Exit
        push buttons being pressed.
    5. sendData method is called when the Send push button is pressed.
      • The message entered by the user is gathered and sent to the server.
    6. closeConnection() method is called.
      1. Notifies the Client to close.
      2. Closes the socket.
      3. Closes the input and output streams.



    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.

    
      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