A

PROJECT

ON

JAVA NETWORK CHATTING
FOR THE  PARTIAL FULFILLMENT OF  B.E  SEVENTH SEMESTER
TO       
           DEPARTMENT OF COMPUTER SCIENCE                                                
                             AND ENGINEERING

Raipur Institute of Technology
Chhatauna ,Mandir Hausaud ,RAIPUR(C.G)-492001

   Approved by                                            Developed by 
 Mrs Kiran Chabbra		                 Arun Shrivastava   
          H.O.D                                               Himanshu Tiwari  
Computer Sci. & Engg.                                   Manish Jain
R.I.T ,RAIPUR(C.G)
                                                                   
Guided by                                			Inspected By
Mrs Nanda Yadav                                          Mr Abhishek Pandey                                                                  
 (Professor,R.I.T.)                                            (Professor,R.I.T.)                                                      

Index
   Description                                            Page No.

Acknowledgement                                                   i.
Certificate              	           		                    ii.
Declaration							           iii.
    Project Description						     1
    Hardware/Software Recommended  		     2
    Output      								     7
    Program Code 							   10	
    Conclusion 								   27
    Bibliography							   29

               

               

                              

   										            i.		

ACKNOWLEDGEMENT

                                           Expressing gratitude is a difficult  task ,and words often fall short of reflecting one’s feelings.It is our  proud privilege , however to  do so and we are undertake this task wit utmost sincerity.
                                         We express our special thanks to our H.O.D  Mrs Kiran Chabbra. Who has given us opportunity to exhibit out talent,through giving us a chance to  make project in JAVA language.
                                       We are ever grateful to the project guide Mrs Nanda Yadav who insipered and guided us in the completion of this project.
                                         Special thanks to Mr Pankaj Pandey(visiting professor Pt R.S.U (M.C.A Dept.)) for his help and support which led to the bug free and efficient java codes.

   

											 ii.

Certificate

This is to certify that project entitled “JAVA NETWORK CHATTING” has been developed by Arun Shrivastava, Himanshu Tiwari & Manish Jain for the partial fulfilment of the B.E 7th Semester (C.S& Engg)Raipur Institute of Technology ,Raipur,affilated to Pt.R.S.S University Raipur and is authentic.

Mrs Kiran Chabbra					Date:
          H.O.D
Computer Sci. & Engg.
 R.I.T ,RAIPUR(C.G)

                                           iii.

Declaration

We here  by declare that the project entitled “JAVA NETWORK CHATTING “ has been developed by us for the partial fulfillment of B.E. 7th  Semester (C.S & Engg.)
R.I.T. Raipur,affliated to Pt. R.S.S University and has not been submitted any where else of the any examination.

							  Yours Sincerely,

         						   Arun Shrivastava
      							   Himanshu Tiwari
                                                        Manish Jain
						 	  (C.S&Engg.7thSem.)	

1.

2.
Project Description

1	For chatmulti-user 
2	Written for jdk 1.0.2 works with jdk 1.0.2 and above (but uses deprecations and only AWT)

This is a simple socket based chat program. It is composed of a server and a client, both console version and a graphical one.

The Server is also supported by a Hit Counter.The Hit Counter displays the no. of Hits(i.e request made for connection) made to the server by the Clients. 

The program can be run on a LAN or over the Internet (provided packet can pass firewall and/or proxies). 

The program can allow any number of chatters (actually the maximum is 70, but can be recompiled for more)

3.
The Project contains:-

chat.txt (this file)
source/	the dir with source code
bin/	the dir with the classes

The Server

start the server on the server machine:

>java ChatServer OR by running chatserver.bat file.

Note
The port is  by default 2004,	this will put up a server 
 listening on the specified port of the server machine.

The Client

On each client machine start a client:-

>java ChatClient [intadx]	//console version
>java ChatApplet [intadx]            //AWT version

4.
where intadx#:	TCP/IP server adx, is default localhost
Note  
The port#: is by default 2004

Once the client is up, first string you input will be your nick name. From now on any string inputted will be a message that will be broadcasted to others.
To finish inputting a string simply push Enter.
You will see your messages (preceded by ">") and others' messages (preceded by "<").

This project is based on the Client-Server architecture.Client-Server architecture is a three tier or three layered namely:-
1.	Presentation Layer:-This layer does the job of authorisation,authentication & accounting .
2.	Business Layer:- This layer is concerned with the job of connectivity and transmission.
3.	Data Layer:-This layer deals with the data base.

]

						5.

						6.

HARDWARE/SOFTWARE RQUIREMENT

1. C.P.U                       PENTIUM- 1&ABOVE

2. RAM                        MIN 32MB

3.HARDDISK              1.2 GB

4.SOFTWARE             JDK1.0.2 & ABOVE

5.O.S(OPERATING SYSTEM)     WIN-NT 4.0

7.

8.

9.

10.

11.
//*CHATAPPLET.JAVA*// 

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

public class ChatApplet extends Frame implements Runnable
{
        static String command;	//shared resource
	Socket socket;
	static final int portNumber=2004;
	DataInputStream input;
	PrintStream output;
	String alias=null;
	boolean logging=true;
	TextArea textArea;
	TextField comm;
	Label status;
	public static void main(String[] argv) throws IOException
	{
		InetAddress clientAddr;
		if(argv.length==0)
			clientAddr=InetAddress.getLocalHost();
		else
			clientAddr=InetAddress.getByName(argv[0]);

		System.out.println("Connecting to Chat Server at "+clientAddr);
		ChatApplet ca=new ChatApplet(clientAddr);
		Thread t=new Thread(ca);
		t.start();
	}
	public ChatApplet(InetAddress adx)
	{   
		super("RISING CHAT CLIENT");
                //AWT
                setBackground(new Color(255,255,128));
                resize(300,400);      
		setLayout(new BorderLayout());                
                textArea=new TextArea(20,20);
		textArea.setEditable(false);
		comm=new TextField(30);
		status=new Label("Please type in alias to Connect..");
		add("North",comm);
		add("Center",textArea);
		add("South",status);
12
                        command="xXx";
       	            try
		{
			socket=new Socket(adx,portNumber);
			input=new DataInputStream(socket.getInputStream());
			output=new PrintStream(socket.getOutputStream());
		}
		catch(IOException e)
		{			
                     status.setText("Abnormal chat client socket condition:"+e);
			repaint();
		}
	}

	public boolean action(Event e,Object o)
	{
		if(e.target==comm)
		{
			synchronized(command)
			{
				command=comm.getText();
				comm.setText("");
			}
			return true;
		}
		return false;
	}

	public boolean handleEvent(Event evt)
	{
		if (evt.id == Event.WINDOW_DESTROY)
		{
			synchronized(command)
			{
				command="exit";
			}
		}

      		return super.handleEvent(evt);
	}

	public void run()
	{
		show();
		try
13.
{
			doLoop();
			input.close();
			output.close();
			socket.close();
			System.exit(0);
		}
		catch(IOException e)
		{
			status.setText("Abnormal chat client socket condition:"+e);;
			repaint();
		}

	}

	public void doLoop() throws IOException
	{
		String nullString=new String("xXx");
		String data=nullString;
		while(true)
		{

			synchronized(command)
			{
				
				if(!command.equals("xXx") && !command.equals(" "))
				{
					data=command;
					//reset
					command="xXx";
				}
			}	//end synch

			if(!data.equals("xXx") && !command.equals(" ") )
			{
				if(logging)
				{
					
					logging=false;
					alias=data;
					status.setText("Logging  as:"+alias);
					repaint();
					output.println("S"+alias);	//Starting new chat
				}
				else
14.
				{
					status.setText("Sending msg:"+data);
					textArea.appendText(">"+data+"\n");
					repaint();
					output.println("D"+data);	//sending data
				}

				if(data.equals("exit"))
				{
					status.setText("Exiting Chat...");
					repaint();
					output.println("X"+alias);
					break;
				}
			}
			data=input.readLine();
			if(!data.equals("xXx"))
			{
				textArea.appendText("<"+data+"\n");
				repaint();
			}
			data=nullString;
		}
        }
                        public void paint(Graphics g)
                             {
                                 textArea.setFont(new Font("Dialog",Font.BOLD,14)); 
                                 textArea.setBackground(new Color(143,160,252));
                             }
	
}

************************************************************************************************************************************************

			//CHATCLIENT.JAVA

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

public class ChatClient implements Runnable
{

15.
	static String command;	
	Socket socket;
	static final int portNumber=2004;
	Thread commReader=null;

	DataInputStream input;
	PrintStream output;

	String alias=null;
	boolean logging=true;

	public static void main(String[] argv) throws IOException
	{
		InetAddress clientAddr;
		System.out.println("Rising Chat Client");
		if(argv.length==0)
			clientAddr=InetAddress.getLocalHost();
		else
			clientAddr=InetAddress.getByName(argv[0]);
		System.out.println("Connecting to Chat Server at "+clientAddr);
		ChatClient cc=new ChatClient(clientAddr);
		Thread t=new Thread(cc);
		t.start();
	}

	public ChatClient(InetAddress adx)
	{
		CommandReader cr=new CommandReader(this);
		commReader=new Thread(cr);
		command="xXx";
		try
		{
			socket=new Socket(adx,portNumber);
			input=new DataInputStream(socket.getInputStream());
			output=new PrintStream(socket.getOutputStream());
			commReader.start();
		}
		catch(IOException e)
		{
			System.out.println("Abnormal chat client socket condition:"+e);;
		}
	}

	public void run()
	{
16.
		try
		{
			doLoop();
			input.close();
			output.close();
			socket.close();
			System.exit(0);
		}
		catch(IOException e)
		{
			System.out.println("Abnormal chat client socket condition:"+e);;
		}

	}

	public void doLoop() throws IOException
	{
		String nullString=new String("xXx");
		String data=nullString;
		while(true)
		{

			synchronized(command)
			{
				
				if(!command.equals("xXx"))
				{
					data=command;
					//reset
					command="xXx";
					
				}
			}	//end synch

			if(!data.equals("xXx"))
			{
				if(logging)
				{
					//first msg
					logging=false;
					alias=data;
					System.out.println(">>Logging  as:"+alias);
					output.println("S"+alias);	//Starting new chat
				}
				else
17.
				{
					if(data.equals("exit"))
					{
						System.out.println(">>Exiting Chat.");
						output.println("X"+alias);
						break;
					}
					else if(data.equals("/list"))
					{
					System.out.println(">>list of connect end users:");    
						output.println("L"+alias);
						break;
					}
					else if(data.equals("/help"))
					{
					System.out.println(">>Help on Chat commands:");
						output.println("H"+alias);
						break;
					}
					else
					{
						System.out.println(">>Sending msg:"+data);
						output.println("D"+data);	//sending data
					}
				}

			}

			data=input.readLine();
			if(!data.equals("xXx"))
			{
				System.out.println("<<"+data);
			}
			data=nullString;
		}
	}

}
************************************************************************************************************************************************

18.
//CHAT CONNECT.JAVA

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

public class ChatConnect implements Runnable 
{
	int index=-1;
	SharedMsg sharedMsg;
	Socket socket;

	DataInputStream input;
	PrintStream output;
	String alias="";
	boolean running=false;

	boolean alive()
	{
		return running;
	}

	public ChatConnect(Socket s,SharedMsg sm,int idx)
	{
		index=idx;
		sharedMsg=sm;
		socket=s;
		try
		{
			input=new DataInputStream(socket.getInputStream());
			output=new PrintStream(socket.getOutputStream(),true);
			
		}
		catch(IOException e)
		{
			System.out.println("Abnormal chat server socket condition 1:"+e);;
		}
	}

	public void run()
	{
		try
		{
			doLoop();
			input.close();
			output.close();
19.
         	socket.close();
		}
		catch(IOException e)
		{
			System.out.println("Abnormal chat server socket condition 2:"+e);;
		}
	}

	public void doLoop() throws IOException
	{
		String line=null;
		String data=null;
		char command='W';
		char ind=(char)index;	//index of sender of msg
		char broad=(char)-1;	//goes to everybody

		running=true;
		while(true)
		{
			//loop: reads in msg, write it onto sharedmsg
			line=input.readLine();
			command=line.charAt(0);
			data=line.substring(1);

			if(command=='X')
			{
				sharedMsg.put(broad+"User: "+data+" Logged Out");
				break;
			}
			else if(command=='S')
			{
				//first msg
				alias=data;
				sharedMsg.put(broad+"New User Logged: "+alias);
			}
			else
			{
				sharedMsg.put(ind+"From "+alias+": "+data);
			}
		}
		//exiting
		running=false;
	}

	//new message arrived, send it over the socket
20.
            public void newMsg(String msg)
	{
		char mitt=msg.charAt(0);		
                String data=msg.substring(1);

		if(mitt!=(char)index)
		{
			//send
			output.println(data);
			output.flush();

		synchronized(System.out)
			{
				System.out.print(".\b");
				System.out.flush();
			}
		}
	}
}
************************************************************************************************************************************************

			//CHATSERVER.JAVA

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

public class ChatServer implements Runnable
{
	static final int maxClients=70;
	static final int portNumber=2004;
	static int numClients=0;
        static int i=0;
        ChatConnect[] chatters;
	Thread me;

	SharedMsg sharedMsg;

	public static void main(String[] argv) 
	{

           //For Hit Counter

           
21.
                 try
                {
     FileReader fr=new FileReader("counter.doc");
     BufferedReader br=new BufferedReader(fr);
     String s;
                      while((s=br.readLine() )!=null)
                          { 
                              int length=s.length();
                              char c[]=new char[length];
                              s.getChars(0,length,c,0);
                              CharArrayReader input1=new CharArrayReader(c);
                              int j;
                              while((j=input1.read())!=-1)
                                    {
                                         i=j;
                                    }
                          }
    fr.close();
    
                }
              catch(Exception e)
                   {}

          //Chat Server

          ChatServer cd=new ChatServer();

        }
	public ChatServer()
	{
		sharedMsg=new SharedMsg(this);
		chatters=new ChatConnect[maxClients];
		//start sending
		me=new Thread(this);
		me.start();

		try
                {
			listen();
		}
		catch(IOException e)
		{
			System.out.println("Abnormal socket condition:"+e);

22.
		}
	}

	public void listen() throws IOException
        {
                
                ServerSocket ss=null;
                
		ss=new ServerSocket(portNumber);
		Socket chatSocket=null;
		System.out.println("Chat Server by ARUN,HIMANSHU & MANISH-2004(7th CS & Engg.,RIT)");
                //System.out.println("Hit Counter Started");
		System.out.println("...listening for connections..");
		while(true)
		{
			
                        chatSocket=ss.accept();

                 String senderIP=chatSocket.getInetAddress().getHostAddress();
                 String senderPort="" + chatSocket.getPort();
                 i++;
 
String clientadd=".client_add(IP:PORT:HIT.C)"+senderIP +":"+ senderPort +":" +i +";" ;
    try{
          String source =clientadd;
          char buffer[]=new char[source.length()];
          source.getChars(0,source.length(),buffer,0);
          FileWriter f1=new FileWriter("file1.doc",true);
          f1.write(buffer);
          f1.close();
       }
   catch(Exception e){}                 
                 
                 System.out.println("Hit Count=" +i);
                 
                 System.out.println("Hit By"+":"+senderIP+":"+senderPort+":");

                 CharArrayWriter f= new CharArrayWriter();
                 char  s=(char) i;
                 f.write(s);
                 FileWriter f2=new FileWriter("counter.doc",true);
                 f.writeTo(f2);
                 f2.close();

23.
                 ChatConnect ct=allocThread(chatSocket);
			synchronized(System.out)
			{
				System.out.println("Allocated new chat server");
			}
		}

	}

	ChatConnect allocThread(Socket s)
	{
		if(numClients<maxClients)
		{
			ChatConnect ct=new ChatConnect(s,sharedMsg,numClients);
			chatters[numClients]=ct;
			Thread t=new Thread(ct);
			t.start();
			numClients++;
			return ct;
		}
		else
			return null;
	}

	public void run()
	{
		char broad=(char)-1;
		String dataNull=new String(broad+"xXx");
		while(true)
		{
			
			for(int i=0;i<numClients;i++)
				if(chatters[i].alive())
				chatters[i].newMsg(dataNull);
		}
	}

	public void refresh() 
	{
        	String data=sharedMsg.get();
		synchronized(System.out) 
		{       
			System.out.println("RECEIVED:"+data);
24.
                         }
		for(int i=0;i<numClients;i++)
		{
			if(chatters[i].alive())
				chatters[i].newMsg(data);
		}
	}

}

************************************************************************************************************************************************
			//COMMANDREADER.JAVA

import java.io.*;

/**
 * Reads from keyboard (STDIN)
 */
class CommandReader implements Runnable
{
	ChatClient chatClient;
	DataInputStream user;

	public CommandReader(ChatClient cc)
	{
		chatClient=cc;
		user=new DataInputStream(System.in);
	}

	public void run()
	{
		System.out.println("Waiting for client side commands...");

		String com=null;
		while(true)
		{
			//reads from keyboard
			try
			{
				com=user.readLine();
			}
			catch(IOException e)
			{
25.
                                    System.out.println("Abnormal reading from user:"+e);
			}
			
			synchronized(chatClient.command)
			{
				chatClient.command=com;
			}
		}
	}
}

************************************************************************************************************************************************

			//SHAREDMSG.JAVA

import java.io.*;
public class SharedMsg
{
	String data="";
	ChatServer chatServer=null;

	SharedMsg(ChatServer cd)
	{
		chatServer=cd;
		
	}

	synchronized String get()
	{
		return data;
	}

	synchronized void put(String s)  
	{
		data=s;
 try{
 String source =s;
 char buffer[]=new char[source.length()];
 source.getChars(0,source.length(),buffer,0);
 FileWriter f1=new FileWriter("file1.doc",true);
 f1.write(buffer);
26.
 f1.close();
 }catch(Exception e){}

		chatServer.refresh();
	}
}

27.

28.
CONCLUSION

                             We hope this project has been developed to its perfect extent and will certainly perform all the function mentioned earlier. Thus this project helps the user to make easy chat  in the local network/internet.

29.

30.

BIBILIOGRAPHY

 BOOKS:-
1.	THE COMPLETE REFERANCE THIRD      EDITION(TMH)PATRICK NAUGHTON,HERVERT SCHILDT
2.	JAVA CERTIFICATION SECOND EDITION (PEARSON)   K.A.MUGHAL&R.W. RASMUSSSEN
WEBSITES:-
1.	WWW.JAVARANCH.COM
2.	WWW.SUN.COM