Java Chat Application – Where Conversations Come Alive!

In this project, we will learn how to create a simple chat application using Java Swing for the graphical user interface (GUI) and sockets for network communication. The chat application will consist of a client-side and a server-side component, allowing users to send and receive messages in real-time. The client and server will establish a socket connection to communicate with each other, and the GUI will provide an intuitive interface for users to interact with the chat application.

About Java Chat Application App

The objective of this project is to demonstrate how to build a basic chat application using Java Swing and socket programming. By the end of this project, you will have a clear understanding of the following concepts:

1. Creating a GUI using Java Swing to design the chat application interface.
2. Establishing a socket connection between the client and server for communication.
3. Implementing input and output streams to exchange messages between the client and server.
4. Handling user actions, such as sending messages and connecting/disconnecting from the chat.
5. Building a multi-threaded application to handle concurrent reading and writing of messages.
6. Implementing basic chat features like sending private messages to specific users.

Prerequisites for Chat Application App Using Java

To follow this project successfully, you should have a basic understanding of the following:

1. Java programming language fundamentals, including classes, objects, and methods.
2. Familiarity with Java Swing for creating GUI applications.
3. Knowledge of socket programming concepts, such as TCP/IP, client-server architecture, and basic networking principles.
4. Experience with multi-threading in Java to handle concurrent operations.
5. An integrated development environment (IDE) like Eclipse or IntelliJ IDEA to write and run Java code.

Download Java Chat Application App Project

Please download the source code of Java Chat Application App Project: Java Chat Application App Project Code.

Steps to Create Chat Application App Project Using Java

Step 1: Implementing Client Class Functions

Step 2: Implementing Server Class Functions

Implementing Client Class Functions:

1. “Client()”: The constructor method initializes the user interface by calling “initializeUI()”.

2. “initializeUI()”: This method sets up the graphical user interface for the client application. It creates a JFrame, JTextArea, JTextField, buttons, and other necessary components. It also adds action listeners to handle button clicks and sets their initial enabled/disabled states.

3. “appendToChatArea(String message)”: This function appends the provided message to the chat area (JTextArea) in the client application.

4. “sendMessage()”: This method is called when the user clicks the send button. It retrieves the text from the messageField (JTextField) and sends it to the server through the PrintWriter.

5. “shutdown()”: This method is called when the user clicks the quit button or wants to close the client application. It closes the socket connection and the input/output streams.

6. “startReading()”: This function continuously reads messages from the server in a separate thread. It uses a BufferedReader to read messages from the server and appends them to the chat area by calling “appendToChatArea()”.

7. “startWriting()”: This function continuously reads user input from the console and sends it to the server in a separate thread. It uses a BufferedReader to read user input and sends it to the server through the PrintWriter.

Here’s the complete code for the Client Class:

package com.TechVidvan;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {

    private Socket socket;
    private BufferedReader br;
    private PrintWriter out;

    private JFrame frame;
    private JTextArea chatArea;
    private JTextField messageField;
    private String username;

    public Client() {
        initializeUI();

    }

    private void initializeUI() {
        frame = new JFrame();
        frame.setTitle("Client");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.getContentPane().setLayout(new BorderLayout());

        chatArea = new JTextArea();
        chatArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(chatArea);
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);

        JPanel inputPanel = new JPanel();
        frame.getContentPane().add(inputPanel, BorderLayout.SOUTH);
        inputPanel.setLayout(new GridLayout(0, 2, 0, 0));

        messageField = new JTextField();
        messageField.setEnabled(false);
        inputPanel.add(messageField);
        
                
                JButton sendButton = new JButton("Send");
                sendButton.setEnabled(false);
                sendButton.addActionListener(new ActionListener() {
                    
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        sendMessage();
                    }
                });
                inputPanel.add(sendButton);
                
                JLabel usernameLabel = new JLabel("Username:");
                inputPanel.add(usernameLabel);
        
                JTextField usernameField = new JTextField();
                inputPanel.add(usernameField);
        
                JButton connectButton = new JButton("Connect");
                connectButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        String usernameInput = usernameField.getText();
                        if (!usernameInput.isEmpty()) {
                            username = usernameInput;
                            connectButton.setEnabled(false);
                            usernameField.setEditable(false);
                            
                        }
                        // Establish connection with the server
                        try {
                        	System.out.println("Sending Request to the server");
                            socket = new Socket("127.0.0.1", 7777);
                            appendToChatArea("[Client]: Connected to server");
                            
                            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                            out = new PrintWriter(socket.getOutputStream());
                            startReading();
                            messageField.setEnabled(true);
                            sendButton.setEnabled(true);
                            messageField.requestFocus();
                            
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }

                    }
                });
                inputPanel.add(connectButton);

        JButton quitButton = new JButton("Quit");
        quitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                shutdown();
            }
        });
        
        inputPanel.add(quitButton);

        
        frame.setVisible(true);
    }

    private void appendToChatArea(String message) {
        chatArea.append(message + "\n");
    }
    
    private void sendMessage() {
        String message = messageField.getText().trim();
        if (!message.isEmpty()) {
            if (message.startsWith("@username:")) {
                out.println(message);
            } else {
                out.println(username + ": " + message);
            }
            out.flush();
            messageField.setText("");
        }
    }
     
    private void shutdown() {
        try {
            socket.close();
            br.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.exit(0);
    }

    public void startReading() {
        Runnable reader = () -> {
            appendToChatArea("Started reading...");
            try {
                while (true) {
                    String message = br.readLine();
                   
                        appendToChatArea(message);
                    
    }
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        new Thread(reader).start();
    }

    public void startWriting() {
        Runnable writer = () -> {
            try {
                BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));

                while (true) {
                    String content = br1.readLine();
                    out.println(content);
                    out.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        new Thread(writer).start();
    }

}

Implementing Server Class Functions

1. “Server()”: The constructor method initializes the user interface by calling “initializeUI()” and sets up the server socket. It also starts reading messages from connected clients and writing messages to them.

2. “initializeUI()”: This method sets up the graphical user interface for the server application. It creates a JFrame, JTextArea, JTextField, buttons, and other necessary components. It adds action listeners to handle button clicks and sets their initial enabled/disabled states.

3. “appendToChatArea(String message)”: This function appends the provided message to the chat area (JTextArea) in the server application.

4. “sendMessage()”: This method is called when the server wants to send a message to connected clients. It retrieves the text from the messageField (JTextField) and sends it to all connected clients through the PrintWriter.

5. “shutdown()”: This method is called when the server wants to shut down. It closes the server socket, socket connections with clients, and the input/output streams.

6. “startReading()”: This function continuously reads messages from connected clients in a separate thread. It uses a BufferedReader to read messages from clients and appends them to the chat area by calling “appendToChatArea()”.

7. “startWriting()”: This function continuously reads user input from the console and sends it to connected clients in a separate thread. It uses a BufferedReader to read user input and sends it to all connected clients through the PrintWriter.

8. “main(String[] args)”: The main method starts the server application and client applications in separate threads.

Here’s the complete code for the Server Class:

package com.TechVidvan;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    ServerSocket server;
    Socket socket;
    BufferedReader br;
    PrintWriter out;

    private JFrame frame;
    private JTextArea chatArea;
    private JTextField messageField;
    private JButton sendButton;
    private String username;

    public Server() {
        initializeUI();
        try {
            server = new ServerSocket(7777);
            appendToChatArea("Server is ready to accept the connection");
            appendToChatArea("Waiting...");
             
//            socket = server.accept();

            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream());

            startReading();
            startWriting();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    /**
     * @wbp.parser.entryPoint
     */
    
    private void initializeUI() {
        frame = new JFrame();
        frame.setTitle("Server");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.getContentPane().setLayout(new BorderLayout());

        chatArea = new JTextArea();
        chatArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(chatArea);
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);

        JPanel inputPanel = new JPanel();
        frame.getContentPane().add(inputPanel, BorderLayout.SOUTH);
        inputPanel.setLayout(new GridLayout(0, 2, 0, 0));

        messageField = new JTextField();
        messageField.setEnabled(false);
        inputPanel.add(messageField);
        
                sendButton = new JButton("Send");
                sendButton.setEnabled(false);
                sendButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        sendMessage();
                    }
                });
                inputPanel.add(sendButton);
                
        
        JLabel usernameLabel = new JLabel("Username:");
        inputPanel.add(usernameLabel);
        
                JTextField usernameField = new JTextField();
                inputPanel.add(usernameField);
        
                JButton connectButton = new JButton("Connect");
                connectButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        String usernameInput = usernameField.getText();
                        if (!usernameInput.isEmpty()) {
                            username = usernameInput;
                            connectButton.setEnabled(false);
                            usernameField.setEditable(false);
                            
                        }
                        // Establish connection with the client
                        try {
                            socket = server.accept();
                            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                            out = new PrintWriter(socket.getOutputStream());
                            appendToChatArea("[Server]: Client connected");
                            startReading();
                            messageField.setEnabled(true);
                            sendButton.setEnabled(true);
                            messageField.requestFocus();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }

                        
                    }
                });
                inputPanel.add(connectButton);

        JButton quitButton = new JButton("Quit");
        quitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                shutdown();
            }
        });
        inputPanel.add(quitButton);

        
        frame.setVisible(true);
    }
    
    private void shutdown() {
        try {
            server.close();
            socket.close();
            br.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.exit(0);
    }


    private void appendToChatArea(String message) {
        chatArea.append(message + "\n");
    }

    public void startReading() {
        Runnable reader = () -> {
            appendToChatArea("Started reading...");
            try {
                while (true) {
                    String message = br.readLine();
                   
                        appendToChatArea(message);
                    
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        new Thread(reader).start();
    }

    public void startWriting() {
        Runnable writer = () -> {
            try {
                BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));

                while (true) {
                    String content = br1.readLine();
                    out.println(content);
                    out.flush();

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        new Thread(writer).start();
    }

    private void sendMessage() {
        String message = messageField.getText().trim();
        if (!message.isEmpty()) {
            if (message.startsWith("@username:")) {
                out.println(message);
            } else {
                out.println(username + ": " + message);
            }
            out.flush();
            messageField.setText("");
        }
    }

    /**
     * @wbp.parser.entryPoint
     */
    public static void main(String[] args) {
        System.out.println("Going to start the server");
        Thread serverThread = new Thread(() -> new Server());

        System.out.println("Client is started");
        Thread clientThread = new Thread(() -> new Client());

        serverThread.start();
        clientThread.start();
    }

}

Java Chat Application Output

java chat application output

chat application output

java chat application app output

java chat application project output

Conclusion

In this project, we have learned how to create a basic chat application using Java Swing and sockets. We covered UI setup, socket communication, message sending and receiving, and user interaction. By following these steps, you can build a functional chat application and expand its features based on your requirements.