Chat Server Implementation

Chat Server Implementation

Introduction:
           Chat server is a stand alone application that is made of combination of two-applications, server application (which runs on server side) and client application (which runs on client side). This application is using for chatting in LAN. To start chatting client  must be connected with the server after which, messages can be broadcast between each and every client. 

SERVER:
                 Server side application is used to get the message from any client and broadcast to each and every client. And this application is also used to maintain the list of users and broadcast this list to everyone.
  • Firstly server program creates a new server socket by the
             ServerSocket ss = new ServerSocket(Port number);
  • After creating the ServerSocket it accepts the client socket and adds this socket into an arraylist.
  • After getting the client socket it creates a thread and enables the DataInputStream for this socket. After creating the input stream it reads the user name and adds it to arraylist and this arraylist object writes into the ObjectOutputStream of each client by using an iterator. 
  • After this process, it creates a new thread and creates one DataInputStream for reading the messages which is sent by the client and after reading the message it creates the DataOutputStream for each socket and writes this message in each client output stream through the iterator.
  • If any client logs out,the server receives the client name and removes it from the arraylist. Further ,it sends this updated arraylist to all clients.
           
CLIENT:
  • In the client side, first the program creates a new socket and specifies the address and port of the server and establishes the connection with the Server.
  • The client, then, creates a new thread and DataInputStream, ObjectInputStream and DataOutputStream for sending the user name and retrieving the list of all users and adds all the user names into its list box through the iterator.
  • Then new thread is created for sending and receiving the messages from the server. This task is done by using DataInputStream and DataOutputStream.
  • When the client logs out it sends its’ name and message i.e. “User_Name has Logged out” and terminates the chatting.

ChatServer.java:

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

public class ChatServer implements Runnable {
   private ChatServerThread clients[]=new ChatServerThread[50];
   private ServerSocket server=null;
   private Thread thread=null;
   private int clientCount=0;

   public ChatServer(int port) {
   try   {
System.out.println("binding to port"+port+",please wait ...");
server=new ServerSocket(port);
System.out.println("server started:"+server);
thread=new Thread(this);
thread.start();
    }
    catch(IOException e)
    {  System.out.println("cannot bind to port"+port+":"+e.getMessage());  }
  }
  public void run() {
  while(thread!=null)  {
     try   {
System.out.println("waiting for a client...");
addThread(server.accept());
     }
     catch(IOException e)
     {
System.out.println("server accept error:"+e);
if(thread!=null)
{
   thread.stop();
   thread=null;
}
      }
    }
  }
  public void stop()
  {
      if(thread!=null)
      {
thread.stop();
thread=null;
       }
   }
   private int findClient(int ID)  {
       for(int i=0;i<clientCount;i++)
      if(clients[i].getID()==ID)
return i;
      return -1;
   }
   public synchronized void handle(int ID,String input)   {
      if(input.equals("quit"))
      {
clients[findClient(ID)].send("quit");
remove(ID);
       }
      else
for(int i=0;i<clientCount;i++)
   clients[i].send(ID+":"+input);
      }

   public synchronized void remove(int ID)   {
      int pos=findClient(ID);
      if(pos>=0)   {
ChatServerThread closing=clients[pos];
System.out.println("removing client thread:"+ID+"at"+pos);

if(pos<clientCount-1)
   for(int i=pos+1;i<clientCount;i++)
      clients[i-1]=clients[i];
clientCount--;

try   {
         closing.close();
}
catch(IOException e)
{   System.out.println("error closing thread;"+e);   }
closing.stop();
      }
   }

  private void addThread(Socket socket)   {
      if(clientCount<clients.length)      {
System.out.println("client accepted:"+socket);
clients[clientCount]=new ChatServerThread(this,socket);
try      {
   clients[clientCount].open();
   clients[clientCount].start();
   clientCount++;
}
catch(IOException e)
{   System.out.println("error opening thread;"+e);   }
      }
      else
System.out.println("client refused;maximum"+clients.length+"reached");
   }
   public static void main(String a[])
   {
      ChatServer server=null;
      if(a.length!=1)
System.out.println("Usage:java ChatServer Port");
      else
server=new ChatServer(Integer.parseInt(a[0]));
   }
}











ChatServerThread.java:

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

public class ChatServerThread extends Thread  {
   private ChatServer server=null;
   private Socket socket=null;
   private DataInputStream In=null;
   private int ID=-1;
   private PrintStream Out=null;

   public ChatServerThread(ChatServer serv,Socket sock)   {
      super();
      server=serv;
      socket=sock;
      ID=socket.getPort();
   }

   public void send(String msg)   {
      Out.println(msg);
      Out.flush();
   }

   public int getID()
   {
      return ID;
   }

   public void run()   {
      System.out.println("Server thread"+ID+"running");
      while(true)   {
try   {      
      server.handle(ID,In.readLine());
}
catch(IOException e)   {
   System.out.println(ID+"error reading"+e.getMessage());
   server.remove(ID);
   stop();
      }
    }
  }
  public void open()throws IOException
  {
            In=new DataInputStream(socket.getInputStream());
            Out=new PrintStream(socket.getOutputStream());
  }

  public void close()throws IOException
  {
            if(socket!=null)
                        socket.close();
            if(In!=null)
                        In.close();
            if(Out!=null)
                        Out.close();
  }
}







ChatClient.java:

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

public class ChatClient implements Runnable   {
   private ChatClientThread client=null;
   private Socket socket=null;
   private DataInputStream console=null;
   private Thread thread=null;
   private PrintStream Out=null;

   public ChatClient(String serverName,int serverPort)   {
      System.out.println("Establishing connection please wait...");
      try   {
            socket=new Socket(serverName,serverPort);
            System.out.println("connected"+socket.toString());
            console=new DataInputStream (System.in);
            Out=new PrintStream(socket.getOutputStream());
            if(thread==null)
            {
                        client=new ChatClientThread(this,socket);
                        thread=new Thread(this);
                        thread.start();
            }
      }
      catch(UnknownHostException e)
      {
            System.out.println("Host unknown"+e.getMessage());
      }
      catch(IOException ioe)
      {
            System.out.println("Unexcepted exception"+ioe.getMessage());
      }
   }

   public void run()   {
      while(thread!=null)      {
try   {
      Out.println(console.readLine());
      Out.flush();
}
catch(IOException e)
{
System.out.println("sending error"+e.getMessage());
stop();
}
      }
   }
   public void handle(String msg)   {
      if(msg.equals("quit"))
      {
System.out.println("good bye, press RETURN to exit...");
stop();
      }
      else
System.out.println(msg);
   }

   public void stop()   {
      if(thread!=null)   {
thread.stop();
thread=null;
      }
      try  {
            if(console!=null)
                        console.close();
            if(Out!=null)
                        Out.close();
            if(socket!=null)
                        socket.close();
      }
      catch(IOException e)
      {
System.out.println("error closing...");
      }
      client.close();
      client.stop();
   }

   public static void main(String args[])   {
      ChatClient client=null;
      if(args.length!=2)
System.out.println("usage:java ChatClient host port");
      else
client=new ChatClient(args[0],Integer.parseInt(args[1]));
   }      
}











ChatClientThread.java:

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

public class ChatClientThread extends Thread   {
   private ChatClient client=null;
   private Socket socket=null;
   private DataInputStream In=null;

   public ChatClientThread(ChatClient cli,Socket sock)
   {
      client=cli;
      socket=sock;     
      try
      {
            In=new DataInputStream(socket.getInputStream());
      }
      catch (IOException e)
      {
            System.out.println("error geting input stream:"+e);
            client.stop();
      }
      start();
   }
  
public void close()
   {
      try
      {
            if(In!=null)
                        In.close();
      }
      catch (IOException e)
      {
            System.out.println("error closing input stream:"+e);
      }
   }

   public void run()
   {
      while(true)
      {
try
{
      client.handle(In.readLine());
}
catch(IOException e)
{
      System.out.println("Listening error"+e.getMessage());
      client.stop();
}
      }
   }
}











ChatServer: OUTPUT
C:\Documents and Settings\cse4y>e:
E:\>cd Lab
E:\Lab>cd ChatServer
E:\Lab\ChatServer>java ChatServer 5123
Binding to port5123,please wait...
Server started:ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=5123]
Waiting for a client...
client accepted:Socket[addr=/192.168.11.66,port=1108,localport=5123]
Waiting for a client...
server thread1108running
client accepted:Socket[addr=/192.168.11.66,port=1121,localport=5123]
Waiting for a client...
Server thread1121running
C:\Documents and Settings\cse4y>e:
E:\>cd Lab
E:\Lab>cd ChatServer
E:\Lab\ChatServer>java ChatClient cselab3-17 5123
Establishing connection .Please wait...
connected:Socket[addr=cselab3-17/192.168.11.66,port=5123,localport=1108]
hi
1108:hi
1121:hello
How are you?
1108:How are you?
C:\Documents and Settings\cse4y>e:
E:\>cd Lab
E:\Lab>cd ChatServer
E:\Lab\ChatServer>java ChatClient cselab3-17 5123
Establishing connection .Please wait...
connected:Socket[addr=cselab3-17/192.168.11.66,port=5123,localport=1121]
1108:hi
hello
1121:hello
1108:How are you?