Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create Chat Application in Java

In this tutorial, we will learn how to create a Chat Application making use of the Java.

You may have seen one of the many Java-based chat systems that have popped up on the Web. After reading this article, you'll understand how they work -- and know how to build a simple chat system of your own.

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. The chat uses TCP/IP sockets to communicate, and can be embedded easily in a Web page.

Building a chat client

We start with a simple graphical chat client. It takes two command-line parameters -- the server name and the port number to connect to. It makes a socket connection and then opens a window with a large output region and a small input region.

Example result

Figure 1: Example result

The ChatClient interface

After the user type’s text into the input region and hits Return, the text is transmitted to the server. The server echoes back everything that is sent by the client. The client displays everything received from the server in the output region. When multiple clients connect to one server, we have a simple chat system. Let us understand the process with the help of the JavaScript code.

Listing 1: Packages

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

Listing 2: The receiver class

class Receiver implements Runnable {
                Thread activity = new Thread(this);
                MulticastSocket so;
                JTextArea txt;
        Receiver(MulticastSocket sock, JTextArea txtAr) {
                so = sock;
                txt = txtAr;
                activity.start();
                }

Here is our class that will represent the data we recieve :> MulticastSocket. This is something we will need if we want to have computers communicating each other. Since we are going to use a server holding up this client...So the MulticastSocket would be your "real" ip to the users.

Listing 3: Running the application

public void run() {
                        byte[] data = new byte[1024];
                        while(true)
                                try {
                                        DatagramPacket packet = new DatagramPacket(data,data.length);
                                        so.receive(packet);
                                        String mess = new String(data,0,packet.getLength());
                                        txt.append(mess+ "\n");
                                }

                                catch(IOException e) {
                        break;
                }
        }
}

While running we need to have something that actually will respond to our needs and so. Hence we send data in form of byte. You can change if you want to something else like long or so. Our data, will be represented as text lines.

Listing 4: The Constructor and GUI base

public class JChat extends JFrame implements ActionListener {
                String name;
                InetAddress iadr;
                int port;
                MulticastSocket so;
                JTextArea txt = new JTextArea();
                JScrollPane sp = new JScrollPane(txt);
                JTextField write = new JTextField();
                JButton quit = new JButton("Go Offline");
                public JChat(String username, String groupAdr, int portNr) throws IOException {
                        name = username;
                        iadr = InetAddress.getByName(groupAdr);
                        port = portNr;
                        so = new MulticastSocket(port);
                        so.joinGroup(iadr);
                        new Receiver(so,txt);
                        [B]sendMess[/B]("Online");
                        setTitle("Chatting with "+ name);
                        txt.setEditable(true);
                        add(quit,BorderLayout.NORTH);
                        add(sp,BorderLayout.CENTER);
                        add(write,BorderLayout.SOUTH);
                        quit.addActionListener(this);
                        write.addActionListener(this);
                        setSize(400,250);
                        setVisible(true);
                        setDefaultCloseOperation(EXIT_ON_CLOSE);
                }

Here we have our constructor and GUI base for the client. By using standards, such as username and port and IP we can actually send and receive data. With ScrollPane we are able to use the scrolling function that a normal window have when content tend to be more than viewable by standard resolution. Plus we are adding each component to a bordered layout, making it simple for us to just place components and items.

Listing 5: Styling the Chat Window

sendMess method
public void sendMess(String s) {
                        byte[] data = (name + ": " + s).getBytes();
                        DatagramPacket packet = new DatagramPacket(data,data.length,iadr,port);
                        try {
                                so.send(packet);
                        }
                        catch(IOException ie) {
                                Toolkit.getDefaultToolkit().beep();
                                JOptionPane.showMessageDialog(null, "Data overflow !");
                        }
                }

Now, by sending out text lines as bytes through Datagram packets we can view our sent lines... else we will get an overflow(Our Exception...)

Listing 6: The actionListener

public void actionPerformed(ActionEvent e) {
                if(e.getSource()==write) {
                        sendMess(write.getText());
                        write.setText("");
                        }
                else if(e.getSource()==quit) {
                        sendMess("Offline");
                        try {
                                so.leaveGroup(iadr);
                        }
                        catch(IOException ie) {
                                Toolkit.getDefaultToolkit().beep();
                                JOptionPane.showMessageDialog(null, "Data overflow, connection error !");
                                }
                        so.close();
                        dispose();
                        System.exit(0);
                        }
                }

The action listener, will register everything we do by the GUI. Typing and sending it...Also by using our offline button we can exit the application and terminate our connection with the client...

Listing 7: The main code

      public static void main(String[] arg) throws IOException {
                String in = JOptionPane.showInputDialog(null,"What's your name?");
                if(arg.length>0) 
                        in = arg[0];
                new JChat(in,"Add a D-Class IP",9876);
        }
}

Now, with our main we are actually going to start the application and do something creative. While we are using our arg(which is also a container), to store the currently user which makes it Covent.

So by adding our parameters while creating a new JChat(username,D-Class IP,port).

Conclusion

This brings us to the creation on a fantastic chat client. Try implementing the same and confirm in case you want to get it clarified over anything. Hope you like the tutorial.



Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login