August 29, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

A Pattern/Framework for Client/Server Programming in Java

  • June 10, 2002
  • By Usman Saleem
  • Send Email »
  • More Articles »

As you can see, writing a server that handles multiple clients is not difficult at all in Java. I hope the pattern above will provide you with a good start for building servers for your specific tasks. Clients in Java that access these and other servers are even easier to write; I provide a pattern for them, as follows.

Client Development

Java's powerful networking capabilities enable us to build highly sophisticated and complex Internet-capable software. The following pattern for building the client side of a client/server model also uses the Observer pattern; however, here the intent is to send out the messages to Observers, received from the server. The source code is as follows:

//Client.java
//© Usman Saleem, 2002 and Beyond.
//usman_saleem@yahoo.com

package com.usal.clientPattern;

import java.net.Socket;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Observable;


public class Client extends Observable implements Runnable {

    /**
     * Uses to connect to the server 
     */
    private Socket socket;

    /**
     * For reading input from server. 
     */
    private BufferedReader br;

    /**
     * For writing output to server. 
     */
    private PrintWriter pw;

    /**
     * Status of client. 
     */
    private boolean connected;

    /**
     * Port number of server
     */
     private int port=5555; //default port

    /**
     * Host Name or IP address in String form
     */
    private String hostName="localhost";//default host name

    public Client() {
		connected = false;
    }

    public void connect(String hostName, int port) throws IOException {
        if(!connected)
        {
	     this.hostName = hostName;
           this.port = port;
           socket = new Socket(hostName,port);
           //get I/O from socket
           br = new BufferedReader(new         InputStreamReader(socket.getInputStream()));
           pw = new PrintWriter(socket.getOutputStream(),true);

		   connected = true;
           //initiate reading from server...
           Thread t = new Thread(this);
           t.start(); //will call run method of this class
        }
    }

    public void sendMessage(String msg) throws IOException
    {
		if(connected) {
	        pw.println(msg);
        } else throw new IOException("Not connected to server");
    }

    public void disconnect() {
		if(socket != null && connected)
        {
          try {
			socket.close();
          }catch(IOException ioe) {
			//unable to close, nothing to do...
          }
          finally {
			this.connected = false;
          }
        }
    }

    public void run() {
	   String msg = ""; //holds the msg recieved from server
         try {
            while(connected && (msg = br.readLine())!= null)
            {
			 System.out.println("Server:"+msg);
			 //notify observers//
			 this.setChanged();
 //notify+send out recieved msg to Observers
              	 this.notifyObservers(msg);
            }
         }
         catch(IOException ioe) { }
         finally { connected = false; }
    }

    public boolean isConnected() {
		return connected;
    }


    public int getPort(){
            return port;
        }

    public void setPort(int port){
            this.port = port;
        }

    public String getHostName(){
            return hostName;
        }

    public void setHostName(String hostName){
            this.hostName = hostName;
        }

	//testing Client//
    public static void main(String[] argv)throws IOException {
        Client c = new Client();
        c.connect("localhost",5555);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String msg = "";
        while(!msg.equalsIgnoreCase("quit"))
        {
           msg = br.readLine();
           c.sendMessage(msg);
        }
        c.disconnect();
    }
}

The core method of the client pattern is connect(). It creates a connection to the server, gets I/O streams, and initiates the Client as a Thread. The run() method, in turn, starts handling incoming messages from the server and notifying the interested Observer classes about the message received. This enables us to use sendMessage() for sending messages to the server separately.

I do not provide the class that implements the Observer interface here; however, all messages received from the server will be received via the update() method's second argument in the implemented class that has registered the Client class as observable. The above-mentioned Client is a very generic implementation; you will need to customize it according to your needs.

I hope that this article will be of help to you in starting to develop your own custom client/server-based programs. Do let me know of any improvements in this pattern or of any problems/errors you found.

Good luck and happy programming in Java.

Usman Saleem
Muhammad Ali Jinnah University, Islamabad Campus
Islamabad, Pakistan





Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel