Chat room program in java

It had been my dream to create a chat room using my programming knowledge. I tried it once previously using servlets, I could get it work for fast internet connections, but for slow connections, working out the chat application had been a night mare, even with a lot of effort I couldn’t do it.

This time my effort was fruitful. I searched the web for the way in which I can serve multiple clients using java network programming. I got a handy tutorial, which is very easy to follow and explains all the necessary concepts to create the client server application. Here it the line for the tutorial http://carfield.com.hk/document/java/tutorial/socket_chat.pdf

I made some simple modifications to the program given in tutorial to make it look like a chat room. The added features includes:

  1. Entering your name at the starting of the app
  2. Viewing all the people who areĀ availableĀ in the Chat room.
  3. Change the client program from an applet to a stand alone program.

The application contains 3 classes as described in the tutorial. 2 of them(Server and ServerThread) should run in the server side, one should run in the client side(Client).

The code is:

Server1.java

import java.io.*;
import java.net.*;
import java.util.*;
public class Server1
{
private Hashtable outputStreams = new Hashtable();
private ServerSocket ss;
public static String OnlineNames=””;
public Server1(int port) throws IOException
{
listen(port);
}
public static void main(String args[]) throws Exception
{
int port = Integer.parseInt(args[0]);
new Server1(port);
}
public void listen(int port) throws IOException
{
ss = new ServerSocket(port);
System.out.println(“Listening on “+ss);
while(true)
{
Socket s = ss.accept();
System.out.println(“Connection From “+s);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
outputStreams.put(s,dout);
dout.writeUTF(OnlineNames);
System.out.println(OnlineNames);
new ServerThread(this,s);
}
}
Enumeration getOutputStreams()
{
return outputStreams.elements();
}
void sendToAll(String message)
{
synchronized(outputStreams)
{
for(Enumeration e = getOutputStreams();e.hasMoreElements();)
{
DataOutputStream dout = (DataOutputStream)e.nextElement();
try
{
dout.writeUTF(message);
}
catch(IOException ie)
{
System.out.println(ie);
}
}
}
}
void removeConnection(Socket s)
{
synchronized(outputStreams)
{
System.out.println(“Removing connection to “+s);
outputStreams.remove(s);
try
{
s.close();
}
catch(IOException e)
{
System.out.println(“Error in closing “+e);
}
}
}
}

ServerThread.java

import java.io.*;
import java.net.*;
import java.util.*;
public class ServerThread extends Thread
{
private Server1 server;
private Socket socket;
public ServerThread(Server1 server,Socket socket)
{
System.out.println(“Hai”);
this.server = server;
this.socket = socket;
this.start();
}
public void run()
{
try
{
DataInputStream din = new DataInputStream(socket.getInputStream());
while(true)
{
String message = din.readUTF();
System.out.println(message);
boolean name=true;
int len = message.length();
for(int i=0;i<6;i++)
{
if(!(message.charAt(len-i-1)==’^’))
{
name=false;
break;
}
}
if(name==true)
{
String name1 = “”;
int i=0;
while(!(message.charAt(i)==’:’ && message.charAt(i+1)==’:’))
{
Server1.OnlineNames = Server1.OnlineNames+message.charAt(i);
i++;
}
Server1.OnlineNames = Server1.OnlineNames+” “;
}
server.sendToAll(message);
}
}
catch(EOFException e)
{
}
catch(IOException ie)
{
ie.printStackTrace();
}
finally
{
server.removeConnection(socket);
}
}
}

Client1.java

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.applet.*;
import java.io.*;
import javax.swing.*;
public class Client1 extends Frame implements Runnable
{
private TextField tf1;
private TextField tf2;
private TextArea ta;
private TextArea to;
private Socket socket;
private DataOutputStream dout;
private DataInputStream din;
private int count=0;
public Client1(String host,int port)
{
String name= JOptionPane.showInputDialog(null,”Enter Your Name”);
tf1 = new TextField(name+”:”);
tf1.setEditable(false);
tf2 = new TextField();
ta = new TextArea();
to = new TextArea(“People Online:n”,50,16);
ta.setEditable(false);
to.setEditable(false);
tf2.requestFocus();
setLayout(new BorderLayout());
add(“North”,tf1);
add(“South”,tf2);
add(“Center”,ta);
add(“West”,to);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
tf2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
processMessage(ae.getActionCommand());
}
});
try
{
socket = new Socket(host,port);
System.out.println(“Connected to “+socket);
din = new DataInputStream(socket.getInputStream());
dout = new DataOutputStream(socket.getOutputStream());
new Thread(this).start();
processMessage(tf1.getText()+”^^^^^^”);
}
catch(IOException e)
{
System.out.println(e);
}
}
private void processMessage(String message)
{
try
{
dout.writeUTF(tf1.getText()+”:”+message);
tf2.setText(“”);
}
catch(IOException ie)
{
System.out.println(ie);
}
}
public void run()
{
try
{
while(true)
{
String message = din.readUTF();
if(count==0 && !(message.equals(null)))
{
System.out.println(message);
String[] names = message.split(” “);
int i=0;
while(i<names.length)
{
to.append(names[i]+”n”);
i++;
}
count++;
}
else
{
boolean name=true;
int len = message.length();
for(int i=0;i<6;i++)
{
if(!(message.charAt(len-i-1)==’^’))
{
name=false;
System.out.println(message.charAt(len-i-1));
break;
}
}
if(name==false)
{
ta.append(message+”n”);
}
else
{
String name1 = “”;
int i=0;
while(!(message.charAt(i)==’:’ && message.charAt(i+1)==’:’))
{
name1 = name1+message.charAt(i);
i++;
}
to.append(name1+”n”);
}
}
}
}
catch(IOException ie)
{
System.out.println(ie);
}
}
public static void main(String args[])
{
Client1 obj = new Client1(“IP Address of server”,portNumber);
obj.setSize(new Dimension(500,500));
obj.setVisible(true);
obj.setTitle(“Chatting Client”);
}
}

first try to understand the programs given in the tutorial. Understand them. Create them, compile and get them executed.

Them come to these programs…… it will be very easy and you may contribute to make these programs better by some means.

I tested it…. It works perfect:-). So glad to get my application working online. I could chat with 2 of my friends sitting in Hyderabad from my hostel without any website or messenger. Creating an app that runs on more than on machine is a great experience. Enjoying my success……:-)

Future Work:

I didn’t code for removing the person’s name from the “People Online” when one goes off line from the chat room. This contribution can be very useful. I am going to give it a try on another day.

About these ads

5 Responses to “Chat room program in java”

  1. How to run this? Do I need to configuer IP and port number in both Server and client. When I copied your code in my eclipse,I got an error in Server class.It says ” The constructor ServerThread(Server1, Socket) is undefined. “.But thats not true because constructor is defined in ServerThread class.
    If you know whats the problem.Can you please guide me.Thanx alot.

  2. I want private chat program complete demo

  3. Deepali Says:

    I want to implement client to server communication, where multiple clients can chat to a server simultaneously in separate chat rooms. but, can u give me some logical idea about it? From the above code it just adds all the client in a single chat room.

  4. Thanks a lot for sharing this with all of us you actually understand what you’re talking about! Bookmarked. Kindly also consult with my web site =). We may have a hyperlink alternate agreement between us

  5. Excellent blog! Do you have any tips and hints for
    aspiring writers? I’m planning to start my own blog soon but I’m a little lost
    on everything. Would you recommend starting with a free platform like WordPress or
    go for a paid option? There are so many options out there
    that I’m totally overwhelmed .. Any ideas? Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: