Tutorial: Basic Client/Server Application


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


  • 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.html"> Client/Servers - An AddressBook Exaample I </a>
    </table>
    </body>
    </html>
  • Download source and tutorial
  • Screenshot
    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
    3. 3/9/2004 9:06:19 AM: Suvoraj Biswas
        Good work, keep it up
        • 3/9/2004 11:30:12 PM: Ronald Holland
        Thanx for your words. I appreciate them.
    4. 4/27/2004 3:35:42 PM:
        Many many THANKS, the code helped me in my assignment
    5. 5/1/2004 7:08:19 AM: Barbulescu Mihai
        I will use the code to get started in learning java. tks
    6. 5/30/2004 7:29:03 PM:
        Cant express my gratitude to you mate. Would still like to "zip" it all in a warm thank you. Especially for the simple yet powerful tutorial. God bless you.
    7. 6/21/2004 8:06:42 PM:
        Great app. I'm just learning java and this has been very helpful.
        Keep the good work comming.
        Thanks a lot.
        Fernando
    8. 8/3/2005 3:35:25 AM: Arif
        I'm very interesting with this code.
    9. 12/4/2006 2:55:34 AM: Fanfan
        Hi, this is a very good program! But can I use it for client to server, then server send to another client chatting?
    10. 4/1/2007 10:37:22 PM: cxh
        good example!
    11. 1/18/2009 5:02:19 AM: Tanushree
        I am a new learner . this has been a precious help to me (If this comment was disrespectful, please report it.)
    12. 1/22/2009 2:47:59 AM: animesh
        it helps the basics communication between client & server. gooooood
  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?
  • 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?
  • Definition

    Introduction

    In this tutorial, we will show how to build a basic client/server application 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 CS Hardware Store III is a tutorial on how to build a more advanced Client/Server application.

    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 |     
                             +---+     +---+
    
     
    Figure 1: Basic two-tier client/server application


    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

    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 to receive that signal. Sockets allow computers to communicate with each other. A socket is an endpoint that allows communication between two computers.

      
    Socket(InetAddress address, int port)
              Creates a stream socket and connects it to the specified port 
                  number at the specified IP address.
     
              Parameters:
                  address   - the remote address
                  port      - the remote port
      
    Figure 2: Declaring a Socket


    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.
     
              Parameters:
                  port     - the local TCP port
                  backlog  - the listen backlog
                  bindAddr - the local InetAddress the server will bind to
      
    Figure 3: Method 2 for Declaring a Socket


    In the next section, we will describe the requirements for our Client-Server application.

    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. Use a class that extends WindowAdapter to respond to the closing of the JFrame.
    What is a template? In the next section, we will explore the concept of a template.

    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  */
        }
    }
    
      
    Figure 4: Templates for Client and Server


    What should the structure of our Client-Server application look like? We will explore this concept in the next section.

    Proposed Structure

    The proposed Basic Client/Server 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()         |   +---+     +---+    | ServerRun()       |          
     +-------------------+                      +-------------------+   
     | RunClient()       |                      | closeConnection() |      
     +-------------------+                      +-------------------+   
     | closeConnection() |                      | main()            |                            
     +-------------------+                      +-------------------+
     | main()            |                      | actionPerformed() |                                  
     +-------------------+                      +-------------------+   
    
      
    Figure 5: Two-Tier Basic Client/Server Application Structure


    The Client Methods perform the following:

    Client Methods
    Method Description
    tcpClient() The tcpClient constructor initializes the tcpClient object. The The logic is:
    1. Call the setup() method to set up the application's GUI
    2. Call the connect() method to set up a connection to the Server
    3. Call the RunClient() method to declare the ServerSocket
    4. Call the RunClient() method to close the connection to the Server
    setUp() this method is used to setup and allocate the GUI objects. The logic is:
    1. Creates JButtons
    2. Creates JPanels
    3. Creates JLabels
    4. Adds Action Listeners to the JButtons
    5. Sets the size for the JFrame
    6. Sets the location for the JFrame
    7. Makes the JFrame visible
    connect() The connect() method does the intialization of the client
    1. socket on localhost and port 5050
    2. Close socket to the server.
    3. Close application
    run() he RunClient() method in the client reads and writes data to the server. The logic is:
    1. Declare a Reader to read data from the Server
    2. Declare a Writer to write data to the Server
    closeConnection() is used to close the socket connection and the input/output streams. The logic
    1. Send a request to the Server to quit
    2. Close the socket
    3. Close the reader
    4. Close the writer
    5. Close the application
    main() This method is the main entry point called by the JVM. The logic is:
    1. Instantiate a tcpClient object
    2. Add a Window Listener
    Figure 6: Client Method


    The Server Methods perform the following:

    Server Methods
    Method Description
    tcpServer() This is the class constructor used for initialization. The logic is:
    1. Call the setup() method to set up the application's GUI
    2. Call the ServerRun() method to declare the ServerSocket
    setUp() The setUp() method does the intialization for the application. The logic is:
    1. Declare JButton
    2. Set Back round and fore ground Color
    3. Declare a button panel - JPanel
    4. Add button panel to the bottom of the frame using BorderLayout.SOUTH
    5. Add a Window Listener
    6. Set the frame size
    7. Set the location of the frame
    8. Make the frame visiable
    ServerRun() this method is used to create the server socket, input/output streams and to listen for input from the socket. The logic is:
    1. Declare a ServerSocket
    2. Send a message that Server is waiting for Client on specified port
    3. Loop while true (connection is open)
    4. Use accept()method to Listens for a connection to be made to the specified socket and it is accepted.
    5. Send a message indicating that connection has been accepted
    6. Set up a reader to read messages from Client
    7. Set up a writer to write messages to Client
    8. Loop while reading and responding to Client messages
    9. Close Client connection on Client request
    closeConnection() is used to close the socket connection and the input/output streams.
    1. Close server_socket.
    2. Close application
    main() this is the entry point for the server application.
    actionPerformed() this method responds to the exit button being pressed on the tcpServer frame.
    1. Listen for a request to shut down the Server application
    Figure 7: Server Method


    In the next section, we will describe sockets.

    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 8: Two Tier Socket Application


    In the next section, we will describe how we use sockets to build a server.

    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.
    In the next section, we will describe how we use sockets to build a client.

    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 );
    Figure 9: How do we create a client GUI?

    How do we create a client 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 10: How do we create a client in Java

    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() ;
    
           run() ;
        }
    
        public  void setup() {
    
        }
    
        public void run() {
           
        }
    
       /**
        * 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(); }
       }
    
    }
    
      
    Figure 11: How do we put it together to build a server

    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 ServerRun 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.
        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.
          • When a message is received, the Server acknowledges the receipt of the message by sending a
            message to the Client.
          • If a message is received that requests that the Server Quit, the Server will close it socket.
    Figure 12: How does the Server work?

    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() ;
    
          run() ;
    
          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 run() {
          
       }
    
       /**
        * This method responds to the send, cancel or exit button
        *  being pressed on the tcpClient frame.
        */
       public void actionPerformed( ActionEvent e )    {
          if ( e.getSource() == clear ) {
             enterBox.setText( "" );
          }
          // get user input and send it to server
          else if ( e.getSource() == send ) {
             sendData( enterBox.getText() );
             display.append( "\n" +  enterBox.getText() ) ;
          }
          else if ( e.getSource() == exit ) {
             closeConnection() ;
          }
       }
    
       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(); }
       }
    
    }
    
    
     
    Figure 13: How do we put it together to build a Client?

    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
        • Clear
        • Send 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.
    Figure 14: How does the Client work?



    Definition

    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.

    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