Sunday, 23 September 2012

Chat Application in Java

This program was developed to demonstrate the functioning of a multi-threaded server in Java. The application consist of two parts.
  1. A muti-threaded server
  2. A client User Agent
There will be one instance running of the Server program and there can be multiple instances running of the client program, communicating with each other through the server program.

Here is the code.

ChatServer.java

import java.net.*;
import java.io.*;

class ChatServer
{
 static ServerSocket ss;
 static Socket cs;
 static ChatClients[] ct = new ChatClients[10]; 
 
 
 public static void main(String[] args)
 {
  try
  {
   int port = Integer.parseInt(args[0]);
   ss = new ServerSocket(port);

   while(true)
   {
    cs = ss.accept();
  
    for(int i=0; i<ct.length; i++)
    {
     if(ct[i]==null)
     {
      ct[i] = new ChatClients(cs, ct);
      System.out.println("A new client has been connected. Client's ID is : " + i);
      break;
     }
    }

   }  
   
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
 }  
}

class ChatClients implements Runnable
{

 Socket cs = null;
 DataInputStream is = null;
 PrintStream os = null;
 ChatClients[] ct;
 
 ChatClients(Socket s, ChatClients[] t)
 {
  cs = s;
  ct=t;
  new Thread(this).start();
 }

 public void run()
 {
  try
  {
   is = new DataInputStream(cs.getInputStream());
   os = new PrintStream(cs.getOutputStream());

   os.println("Enter your name : ");
   String name = is.readLine();

   os.println("Hello "+name+" to our chat room.\nTo leave enter /quit in a new line."); 
   
   //Send everyone I have joined

   for(int i=0; i<ct.length; i++)
   {
    if(ct[i]!=null && ct[i]!=this)
     ct[i].os.println(name + " has entered the chat room.");
   }

   //Send msgs
   while(true)
   {
    String msg = is.readLine();

    if(msg.startsWith("/quit"))
     break;

    for(int i=0; i<ct.length; i++)
    {
    if(ct[i]!=null && ct[i]!=this)
     ct[i].os.println("<" + name + "> " + msg);
    }
   }

   //Send everyone I am leaving
   for(int i=0; i<ct.length; i++)
   {
    if(ct[i]!=null && ct[i]!=this)
     ct[i].os.println(name + " is leaving the chat room.");
   }


   //close connection
   os.println("**Bye");

   for(int i=0; i<ct.length; i++)
   {
    if(ct[i]==this)
    {
     ct[i] = null;
     System.out.println("Client ID " + i + " has left the chat room");
     break;
     
     
    }
   }

   is.close();
   os.close();
   cs.close();

    
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
 }
}

ClientApp.java

import java.io.*;
import java.net.*;

class ClientApp implements Runnable
{

 static Socket cs = null;
 static PrintStream os = null;
 static DataInputStream is = null;
 static BufferedReader br = null;
 static boolean closed = true;  

 public static void main(String[] args)
 {
  try
  {
   int port = Integer.parseInt(args[1]);

   cs = new Socket(args[0], port);

   is = new DataInputStream(cs.getInputStream() );
   os = new PrintStream(cs.getOutputStream());
   br = new BufferedReader(new InputStreamReader(System.in));

   closed=false;

   //Now start thread for readin server responses
   new Thread(new ClientApp()).start();


   //you can write till the connection is not closed from servers end

   while(!closed)
   {
    os.println(br.readLine());    
   }

   is.close();
   os.close();
   cs.close();   
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }  
 }

 public void run()  //this is for keep on reading response from server
 {
  try
  {
   String responseMsg = null;

   while ((responseMsg = is.readLine())!=null)
   {
    System.out.println(responseMsg);
 
    if(responseMsg.startsWith("**Bye"))
     break;    
   }

   closed = true;
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
 }
}

How to execute ?

  1. Copy the server code and save the file with name ChatServer.java
  2. Copy the client application code and save the file with name ClientApp.java
  3. Compile both the files >javac ChatServer.java and  >javac ClientApp.java 
  4. Start the server program and pass it a command line argument, a number specifying the port on which server process will execute. >java ChatServer 1111 , here 1111 is the port number.
  5. Start a client program and pass command line arguments the URL to which you wish to connect (here localhost) and the port number on which the server process in running (in our case 1111) >java ClientApp localhost 1111
  6. Specify your name and join the chat room.
  7. Use step 5 & 6 to start many more instances (users) of the client application.

Chat Application Snapshot

Do you like this article?