Java

 

 

Introduction

In this tutorial, we will create a simple chat application using Java programming language. The main objective is to demonstrate how to build a basic client-server chat system where one user can send messages to another through a simple console-based interface.

The application consists of two parts: the server program and the client program. The server listens for incoming messages from clients, while the client sends and receives messages to and from the server.

Objective

  • Understand how to use Java for networking (Sockets).
  • Create a basic server-client communication model using TCP/IP.
  • Build a simple messaging system in Java.

Code

Server Program

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

public class ChatServer {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(1234);
            System.out.println("Server started, waiting for client...");
            
            Socket socket = serverSocket.accept();
            System.out.println("Client connected: " + socket.getInetAddress());

            // Input and Output streams for client communication
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

            String message;
            while (true) {
                message = in.readLine();
                if (message.equalsIgnoreCase("bye")) {
                    System.out.println("Client disconnected");
                    break;
                }
                System.out.println("Client: " + message);
                out.println("Server: " + message);
            }

            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Client Program

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

public class ChatClient {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost", 1234);
            System.out.println("Connected to the server...");

            // Input and Output streams for client communication
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));

            String message;
            while (true) {
                System.out.print("You: ");
                message = userInput.readLine();
                out.println(message);

                if (message.equalsIgnoreCase("bye")) {
                    System.out.println("Disconnected from the server.");
                    break;
                }

                String response = in.readLine();
                System.out.println(response);
            }

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

Explanation of the Program Structure

The program consists of two main components: ChatServer and ChatClient.

  • ChatServer: This program listens for incoming connections on port 1234 using a ServerSocket. Once a client connects, it creates input and output streams for communication and listens for messages from the client. It responds to each message received and prints it to the console. The server continues to listen until it receives the “bye” command.
  • ChatClient: The client connects to the server at “localhost” on port 1234 using a Socket. It prompts the user for input, sends messages to the server, and displays the server’s response. It also handles disconnecting when the user sends the “bye” command.

How to Run the Program

    1. Make sure you have Java installed on your computer.
    2. Save the server code in a file called ChatServer.java and the client code in a file called ChatClient.java.
    3. Open a terminal or command prompt, navigate to the directory where the files are located, and compile both files:
javac ChatServer.java
javac ChatClient.java
    1. Run the server program first:
java ChatServer
    1. Then, run the client program in another terminal or command prompt:
java ChatClient
  1. You should now be able to send and receive messages between the server and client. Type “bye” to close the connection.
© 2025 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)