Chat Application In Java




Chat Application In Java

This is to certify that the Short term project entitled ³Chat Application in java´ being Submitted to the CDAC NOIDA towards the fulfillment for the degree of Bachelor of Technology in Information Technology, is a bonafide record of their own work and has been successfully completed under my supervision



Under the guidance ofMr.Rajiv Yadav Mr.Partha P Chattaraj

Chat Application In Java


We take this opportunity to express our gratitude to all those people who extended their cooperation and played an important role in successful completion of this project.

We express our sincere thanks to Mr.Rajiv Yadav, for providing invaluable support and guidance throughout the project. We would like to express my gratitude to our Mr.Partha P Chattaraj They imparted great help and technical guidance at each and every step of the project to make it success. The efforts put by us would not be fruitful if it were not for the people around us, who encouraged us at all the times.

Date:25.7.2011 Paras Kumar Sharma

After reading this article. The ChatClient interface After the user types text into the input region and hits Return. the text is transmitted to the server. When multiple clients connect to one server. Building a chat client We start with a simple graphical chat client.Chat Application In Java Building an Internet chat system Multithreaded client/server chat -.and know how to build a simple chat system of your own.the Java way You may have seen one of the many Java-based chat systems that have popped up on the Web. . For reference. you can jump right in and simply refer to the sidebar for reference. The client displays everything received from the server in the output region. If you're already well-versed in Java. It makes a socket connection and then opens a window with a large output region and a small input region. though. If you're still getting up to speed. we have a simple chat system.the server name and the port number to connect to. It takes two command-line parameters -. and can be embedded easily in a Web page. The server echoes back everything that is sent by the client. take a look at the sidebar first. This simple example of a client/server system is intended to demonstrate how to build applications using just the streams available in the standard API. we provide a sidebar explaining Java network programming components that are relevant to this application. you'll understand how they work -. The chat uses TCP/IP sockets to communicate.

*.awt. this is typical for a graphical application. import java. add ("South"..setEditable (false).*. public ChatClient (String title. We implement the Runnable interface so that we can start a Thread that receives messages from the server. as described.start ().net. We then set up our simple user interface. // public boolean handleEvent (Event e) . add ("Center". public class ChatClient extends Frame implements Runnable { // public ChatClient (String title. import java. listener = new Thread (this). The constructor performs the basic setup of the GUI. consisting of the TextArea output and the TextField input. } The ChatClient class extends Frame. } The constructor takes three parameters: a title for the window. handling user interaction. // public void run () . OutputStream o) { super (title). OutputStream o) . This involves setting up a basic user interface. and receiving messages from the server.. and start a Thread listener that accepts messages from the server. this.Chat Application In Java Class ChatClient This class implements the chat client. protected TextArea output.*. InputStream i. The ChatClient communicates over the specified streams. output. setLayout (new BorderLayout ()).requestFocus ().o = new DataOutputStream (new BufferedOutputStream (o)). import java. an input stream. the run() method receives messages from the server. input = new TextField ()).. the handleEvent() method handles user interaction.i = new DataInputStream (new BufferedInputStream (i)). and an output stream. this. .. input.. // public static void main (String args[]) throws IOException . and the main() method performs the initial network connection. protected TextField input. pack (). protected DataInputStream i. We layout and show the window.. protected Thread listener. we create buffered data streams i and o to provide efficient higher-level communication facilities over these streams. output = new TextArea ()). show ().. protected DataOutputStream o. InputStream i.

return true.printStackTrace (). } } catch (IOException ex) { ex. An IOException could occur if the connection to the server has been lost.stop ().printStackTrace(). input. Note that we perform all of the cleanup in a finally clause. we print out the exception and perform == Event. we first assign our listener reference to this Thread to null. hide (). We don't close the window immediately. } catch (IOException ex) { ex. and close the OutputStream o to ensure that the connection is closed. In that event. When a String arrives. We then hide the input field and call validate() so that the interface is laid out again.ACTION_EVENT)) { try { == input) && (e. we sit in an infinite loop reading Strings from the input stream. try { o. } catch (IOException ex) { ex. .id == Event.WINDOW_DESTROY)) { if (listener != null) listener. validate (). Note that this will be signalled by an EOFException from the readUTF() method.Chat Application In Java public void run () { try { while (true) { String line = i. this indicates to the rest of the code that the thread has terminated.appendText (line + "\n").readUTF ().hide ().printStackTrace (). o. the assumption is that the user may want to read the session even after the connection has been lost.setText ("").arg). listener. output.close (). To clean up. } } } When the listener thread enters the run method. we append it to the output region and repeat the loop. } input. so this will occur whether an IOException occurs here or the thread is forcibly stopped.stop ().target == this) && (e.writeUTF ((String) e. } else if ((e. } finally { listener = null. public boolean handleEvent (Event e) { if ((e.flush ().

.Chat Application In Java return true. and we create a ChatClient connected to the socket's streams.length != 2) throw new RuntimeException ("Syntax: ChatClient <host> <port>"). we ensure that the correct number of arguments have been supplied.getInputStream (). The output stream is a DataOutputStream. It is hardwired to read and write Strings in UTF format. It is up to the programmer to take care of this task. ChatServer. s. The ChatHandler class actually does the work of listening for messages and broadcasting them to all connected clients. Integer. so we can use writeUTF() to send a String. One thread (the main thread) handles new connections. and there is a thread (the ChatHandler class) for each client. } return super. Building a multithreaded server We now develop a chat server that can accept multiple connections and that will broadcast everything it reads from any client. If an IOException occurs the connection must have failed.handleEvent (e). we need to check for two significant UI events: The first is an action event in the TextField. which means that the user has hit the Return key. Socket s = new Socket (args[0].getOutputStream ()). public static void main (String args[]) throws IOException { if (args. There are two classes in this program: the main class. so we stop the listener thread. The second event is the user attempting to close the window. Creating the socket may throw an exception that will exit this method and be displayed. is a server that accepts connections from clients and assigns them to new connection handler objects. When we catch this event. then call flush() to ensure that it is sent immediately. we open a Socket to the specified host and port.parseInt (args[1])). we write the message to the output stream. } In the handleEvent() method. this will automatically perform all necessary cleanup. } The main() method starts the client. new ChatClient ("Chat " + args[0] + ":" + args[1]. we stop the listener thread and hide the Frame. s.

and a main() method that actually starts import java.Chat Application In Java The chat system framework Every new ChatClient will connect to the ChatServer.*. Within the ChatHandler class. while (true) { Socket client = public ChatServer (int port) throws IOException { ServerSocket server = new ServerSocket (port).*. } This class is a simple standalone application. c. public class ChatServer { // public ChatServer (int port) throws IOException .start (). } } ... Class ChatServer This class is concerned with accepting connections from clients and launching handler threads to process them.println ("Accepted from " + client. ChatHandler c = new ChatHandler (client). this ChatServer will hand the connection to a new instance of the ChatHandler class that will receive messages from the new client.accept (). a list of the current handlers is maintained.*. System. We supply a constructor that performs all of the actual work for the class. the broadcast() method uses this list to transmit a message to all connected ChatClients.getInetAddress ())..out. import java. import java.util. // public static void main (String args[]) throws IOException .

We must receive messages from the client and re-send these to all other connections.Chat Application In Java This constructor. we create a new instance of the ChatHandler class. import java. these provide us with efficient I/O and methods to communicate high-level data types -. public ChatHandler (Socket s) throws IOException { this. } The constructor keeps a reference to the client's socket and opens an input and an output stream. Strings.length != 1) throw new RuntimeException ("Syntax: ChatServer <port>"). } The main() method creates an instance of the ChatServer. we start it with its start() method. public class ChatHandler extends Thread { // public ChatHandler (Socket s) throws IOException . After we have created this handler.. Again. which performs all of the work of the server. passing the new Socket as a We maintain a list of the connections in a static Vector. o = new DataOutputStream (new BufferedOutputStream (s. import java. The constructor accepts a Socket to which we attach. We create a ServerSocket and then sit in a loop accepting clients with the accept() method of ServerSocket.getInputStream ())). performs the actual client processing. This starts a new thread to handle the connection so that our main server loop can continue to wait on new connections. new ChatServer (Integer. we use buffered data streams.getOutputStream ())).*. // public void run () .. public static void main (String args[]) throws IOException { if (args. protected DataOutputStream this i = new DataInputStream (new BufferedInputStream (s. } We extend the Thread class to allow a separate thread to process the associated client. For each connection.util.. called by the new thread.. Class ChatHandler This class is concerned with handling individual connections. This is the port to which clients will connect. . passing the command-line port as a parameter. import java.*. protected Socket s. protected DataInputStream i.parseInt (args[0])). the run() method. is fairly simple.s = s.*.

broadcast (msg).. } } catch (IOException ex) { ex. try { s.stop ().printStackTrace().Chat Application In Java protected static Vector handlers = new Vector (). Thus. protected static void broadcast (String message) { synchronized (handlers) { Enumeration e = handlers. When the loop exits.printStackTrace (). the finally clause is guaranteed to be executed..elements ().removeElement (this).nextElement (). } finally { handlers.writeUTF (message). It is a static variable and so there is one instance of the Vector for the whole ChatHandler class and all of its instances. } catch (IOException ex) { c. finally construct.flush ().. } } } // protected static void broadcast (String message) .o) { c.o. all ChatHandlers can access the list of current connections.hasMoreElements ()) { ChatHandler c = (ChatHandler) e.. while (true) { String msg = i. is a prime use of the try .addElement (this).. otherwise.. Note that it is very important for us to remove ourselves from this list afterward if our connection fails. where it is imperative that an action take place upon completion of a section of code. finally construct. This type of situation. The body of this method receives messages from a client and rebroadcasts them to all other clients using the broadcast() method. } c.. First we add our thread to the Vector of ChatHandlers handlers. } catch (IOException ex) { ex. In this clause. we remove our thread from the list of handlers and close the socket. The run() method is where our thread enters.readUTF (). we therefore perform all of our work within a try . all other handlers will try to write to us when they broadcast information.close (). The handlers Vector keeps a list of all of the current handlers. whether because of an exception reading from the client or because this thread is stopped. public void run () { try { handlers. try { synchronized (c.. } } . catch . while (e.o.

If the server must handle particularly heavy loads. java. this forces the clients to wait until we are done synchronizing. output. you'll notice that once the window fills up with type. protected DataOutputStream o. then we might provide more fine-grained synchronization.setEditable (false).io. then we call the client's stop() method. output = new TextArea ()). add ("South". public void init () { setLayout (new BorderLayout ()). protected Thread listener. This inconvience is due to an AWT bug. Finally. The Enumeration class provides a convenient way to iterate through all of the elements of a Vector. . the client will not be permitted to open a direct Socket connection back to the server. // Applet parameters: // host = host name // port = host port public class ChatApplet extends Applet implements Runnable { protected DataInputStream i.*. the Mac-based Java VM still appears to be teething. this stops the client's thread and therefore performs the appropriate cleanup. in case we try to broadcast to someone who no longer exists. protected TextField input. Note that the writeUTF() method is not synchronized.awt. It also may not work with Netscape for Macintosh. so we must explicitly perform synchronization to prevent other threads from writing to the stream at the same time. additinal lines don't become visible unless you manually scroll downward (using the scroll bar.*.net. ChatApplet Class Note that this Applet will not operate correctly through a firewall or proxy.*. java. Note that if an exception occurs while writing to a ChatClient.*. Our loop simply writes the message to every element of the Enumeration. Within this synchronized block we get an Enumeration of the current handlers. including removing the client from handlers. of course). add ("Center". We don't want people joining or leaving while we are looping. java. import import import import java. protected TextArea output.Chat Application In Java } } This method broadcasts a message to all clients. input = new TextField ()).applet. We first synchronize on the list of handlers.

getInputStream ())). } } catch (IOException ex) { ByteArrayOutputStream out = new ByteArrayOutputStream ().printStackTrace (). if (host == null) host = getCodeBase ().readUTF (). o = new DataOutputStream (new BufferedOutputStream (s.appendText (" connected.setEditable (false). ex. input. Integer. } } public void execute () { try { while (true) { String line = i. Socket s = new Socket (host. } public void run () { try { String host = getParameter ("host").getOutputStream ())). output. ex.parseInt (port)).start ().getHost (). } catch (IOException ex) { ByteArrayOutputStream out = new ByteArrayOutputStream ().appendText (line + "\n"). i = new DataInputStream (new BufferedInputStream (s. } catch (IOException ex) { ex.appendText ("\n" + out). } public void start () { listener = new Thread (this). input.toString ()).\n"). input..requestFocus ().appendText (out. output. String port = getParameter ("port").hide (). try { o.appendText ("Connecting to " + host + ":" + port + ". execute (). output..stop (). output.").printStackTrace (new PrintStream (out)). validate (). } finally { listener = null. listener.printStackTrace (new PrintStream (out)). . if (port == null) port = "9830". } public void stop () { if (listener != null) listener.close (). output. listener = null.Chat Application In Java input.setEditable (true).

such a protocol would encapsulate messages between the client and server by transmitting a header and a body with each message. } else if ((e.WINDOW_DESTROY)) { if (listener != null) listener. A better solution The solution to this problem is to develop an application-layer protocol that defines a more powerful level of dialog between a client and the server. . and the body contains the actual message information. } return super.handleEvent (e). return true.stop ().writeUTF ((String) e.printStackTrace().target == this) && (e. } input. This can be a serious limitation when we want the server to perform a more generalized purpose. Although this certainly makes more sense than breaking everything down into bytes. or when we want to extend the system to handle more than just text. If we wish to communicate different information. there is one drawback to this implementation: We can communicate only single String messages between clients.stop ().Chat Application In Java } } } public boolean handleEvent (Event e) { if ((e. This concept is similar to the headers that can be attached to HTTP requests and == Event. hide ().id == Event. return true. o.flush ().arg). In this article. listener.ACTION_EVENT)) { try { o. then we must change both the client and the server. we have developed a multithreaded broadcast chat server and a simple graphical == input) && (e. Typically. } } Wrapping up Multithreading is essential for servers with any sophistication. } catch (IOException ex) { ex. We used data streams to read and write messages in UTF format. the header identifies the type of the message and the length of the message body.setText ("").

*. we can introduce much more powerful instead of a broadcast-only server. but a message of type MSG_SCRIBBLE may consist of a sequence of Points. . they call a method that attaches appropriate headers and sends the encapsulated message. it can simply discard the message.Single Server-Multiple Client and Single Server-Multiple Client By Using Multithreading.*.*. import java.*.ChatClient Class.. and so the server can relay messages between clients without understanding the format of the message bodies. For example. so that when a client is sending a message. the header identifies the length of each message. we can extend the server to provide unicast and multicast services. is to abstract the protocol behind a set of stream classes. The protocol can be supported explicitly by all applications. then the server does not need to understand these messages. If the application protocol is appropriately defined. it manually inserts the appropriate header information.Chat Application In Java An encapsulated message By providing this meta-information. a message of type MSG_TEXT may consist of simply a String. however. ChatApplet class import java.awt. and much more elegant solution. the client and server system can be extended easily. and the client is then left with much the same interface as before: Clients write messages to a stream.ChatHandler class. import java. The specifics of header construction and insertion can be handled automatically by the stream classes. they can be used to identify a particular client to whom a message should be relayed. import java. Furthermore. but instead of flushing the stream. Implementation When it comes to implementing such an application-layer protocol. Message headers also can be used for other purposes. there are two main options. For this we create a four classes ChatApplet class. if a client does not understand a message of a new type.applet. Headers also can identify control information coming back from the server. An alternative. so the server can provide notification of events such as clients joining and leaving. Chat Applicatiion In Java with Single Server-Single Client. We can add new message types to the protocol without affecting existing class.

add ("Center". protected TextField input. output.setEditable (false). protected TextArea output. add ("South". input = new TextField ()). input. public void init () { setLayout (new BorderLayout ()). protected DataOutputStream o.Chat Application In Java // Applet parameters: // host = host name // port = host port public class ChatApplet extends Applet implements Runnable { protected DataInputStream i. output = new TextArea ()).setEditable (false). protected Thread listener. } public void start () { .

start ().appendText ("Connecting to " + host + ":" + port + ".getHost (). i = new DataInputStream (new BufferedInputStream (s.appendText (" connected. . if (port == null) port = "9830".\n").parseInt (port)).getOutputStream ())).getInputStream ())).stop (). String port = getParameter ("port").Chat Application In Java listener = new Thread (this). } public void stop () { if (listener != null) listener. } public void run () { try { String host = getParameter ("host"). if (host == null) host = getCodeBase ().."). listener. Integer. output. o = new DataOutputStream (new BufferedOutputStream (s. Socket s = new Socket (host. output. listener = null..

output. } catch (IOException ex) { ByteArrayOutputStream out = new ByteArrayOutputStream ().readUTF ().appendText (line + "\n").printStackTrace (new PrintStream (out)).hide (). input.Chat Application In Java input.printStackTrace (new PrintStream (out)).toString ()). ex. execute (). } finally { listener = null.requestFocus (). . output.appendText ("\n" + out). ex. } } public void execute () { try { while (true) { String line = i. output. input. } } catch (IOException ex) { ByteArrayOutputStream out = new ByteArrayOutputStream ().appendText (out.setEditable (true).

.id == Event.WINDOW_DESTROY)) { if (listener != null) listener.flush (). listener.printStackTrace ().ACTION_EVENT)) { try { o. } } } public boolean handleEvent (Event e) { if ((e. } input. } catch (IOException ex) { ex.stop ().stop (). } catch (IOException ex) { == this) && (e. try { == input) && (e.arg).setText ("").writeUTF ((String) e. o. } else if ((e.Chat Application In Java validate ().id == Event.close (). return true.printStackTrace().

net. o = new DataOutputStream (new BufferedOutputStream (s. } } ChatHandler Class import java.*.getOutputStream ())). public class ChatHandler extends Thread { protected Socket s. protected DataOutputStream import java. //making strems b/w public String name.*.util.s = s. return true.Chat Application In Java hide ().io. this. protected DataInputStream i.String name) throws IOException { this. import java. public ChatHandler (Socket s.*.getInputStream ())). } . } return super. i = new DataInputStream (new BufferedInputStream (s.handleEvent (e).

hasMoreElements ()) { ChatHandler c = (ChatHandler) e. public void run () { //String name = s. .toString ().getInetAddress(). o. o.readUTF(). try { Enumeration e = handlers. o. o.nextElement ().name+" is also online.writeUTF("type name of person for chat with one person or group for group chat").flush().flush(). o. while (e.writeUTF("whom do you want to talk any single person or group chat").writeUTF(n). } handlers. String n=new String(c.} broadcast (name + " has joined you.elements ()."). flag=i.flush(). o.flush(). String flag=new String().").addElement (this). o. if (flag!="group"){unicast(flag).Chat Application In Java protected static Vector handlers = new Vector ().

} catch (IOException ex) { ex.removeElement (this). } } } . broadcast (name + " . broadcast (name + " has left. try { s.printStackTrace ().").hasMoreElements ()) { ChatHandler c = (ChatHandler) e." + msg).} */ while (true) { String msg = i.elements (). } finally { handlers. String n=new String(c.readUTF ().printStackTrace().Chat Application In Java /* Enumeration e = handlers.nextElement (). while (e.close (). o.writeUTF(n). } } catch (IOException ex) {

. } catch (IOException ex) { c.flush ().nextElement ().Chat Application In Java protected static void broadcast (String message) { synchronized (handlers) { Enumeration e = handlers.elements (). try { synchronized (c.writeUTF (message). while (e. } c. } } } } protected void unicast(String name) { synchronized (handlers) { Enumeration e = handlers.o.hasMoreElements ()) { ChatHandler c = (ChatHandler) e.stop ().elements ().o) { c.o.

} } } } } ChatClient class import java.writeUTF(str).stop (). try { if(c. o.*.*.name==name) while(true) { String str=i.nextElement ().Chat Application In Java while (e. . import java. } } catch (IOException ex) { o.hasMoreElements ()) { ChatHandler c = (ChatHandler) e.flush ().readUTF().

add ("South". OutputStream o) { super(title).requestFocus (). listener = new Thread (this). input = new TextField ()). this.i = new DataInputStream (new BufferedInputStream (i)). protected TextArea output.o = new DataOutputStream (new BufferedOutputStream (o)).setEditable (false). output = new TextArea ()). setLayout (new BorderLayout ()).Chat Application In Java import java. add ("Center". protected TextField input. input. pack (). public class ChatClient extends Frame implements Runnable { protected DataInputStream i.awt. . protected Thread listener. InputStream i. protected DataOutputStream o.*. public ChatClient (String title. output. this. show ().

readUTF ().printStackTrace (). try { o. } catch (IOException ex) { ex.start ().close (). validate ().Chat Application In Java listener. } } } . input. output. } public void run () { try { while (true) { String line = i.printStackTrace (). } finally { listener = null.appendText (line + "\n").hide (). } } catch (IOException ex) { ex.

} return super.Chat Application In Java public boolean handleEvent (Event e) { if ((e.length != 2) throw new RuntimeException ("Syntax: ChatClient <host> <port>").ACTION_EVENT)) { try { o. } else if ((e. return true.stop ().target == input) && (e. o. } public static void main (String args[]) throws IOException { if ( == Event.writeUTF ((String) e.WINDOW_DESTROY)) { if (listener != null) listener. } catch (IOException ex) { ex. hide ().arg). } input.stop ().id == Event. .printStackTrace(). listener. return true.handleEvent (e).setText ("").target == this) && (e.flush ().

Integer.*. DataInputStream incoming=new DataInputStream(s.parseInt (args[1])). outgoing.getOutputStream()).readLine(). import java. import java. System.out.*.Chat Application In Java String msg. DataInputStream incoming1=new DataInputStream(System.util. s. new ChatClient (msg1. msg1=incoming1. public class ChatServer { . PrintStream outgoing=new PrintStream(s. msg=incoming.*.println(msg).net.getOutputStream ()). } } ChatServer class import java. Socket s = new Socket (args[0].io.msg1.println(msg1).readLine().getInputStream ().getInputStream()).

while (true) { String name. out.getOutputStream ())). //in = new DataInputStream (new BufferedInputStream (client. DataInputStream in=new DataInputStream(client.readLine(). } } public static void main (String args[]) throws IOException { .println ("Accepted from " + //out = new DataOutputStream (new BufferedOutputStream (client. //DataInputStream in. Socket client = server. c. PrintStream out=new PrintStream(client.Chat Application In Java public ChatServer (int port) throws IOException { ServerSocket server = new ServerSocket (port). ChatHandler c = new ChatHandler (client.start ().getOutputStream()).getInputStream ())). name=in.getInputStream()).accept ().getInetAddress ()). System.println("enter your name : ").out.

parseInt (args[0])).Chat Application In Java if (args. new ChatServer (Integer. } } .length != 1) throw new RuntimeException ("Syntax: ChatServer <port>").

Chat Application In Java OUTPUT IS:-Including command prompt and applet window .

Chat Application In Java .

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.