Chat Application

The process of setting up a simple chat application that demonstrates client-server communication using sockets. Our application consists of a server that listens for connections and a client that connects to the server to exchange messages.

Client-Server Chat Application in Java

Client-server chat application in java is foundational in many applications where multiple clients need to communicate with a central server. The server listens for incoming connections from clients, processes their requests, and responds accordingly. This setup is common in various applications, including web servers, database systems, and chat applications.

In this example, we are creating a chat application where:

  • The server waits for client connections and reads messages sent by the client.
  • The client connects to the server, sends messages, and receives responses.
chat application

Setting Up the Server

The server in our application performs the following tasks:

  1. Initialize the Server Socket: The server starts by opening a ServerSocket on a specific port, which in this case is port 3333.
  2. Accept Client Connections: It waits for a client to connect and accepts the connection.
  3. Read and Send Messages: The server reads messages from the client and responds accordingly. This communication continues until the client sends the message “BYE”.
class Server{

    public void startServer() throws IOException {
        // Start a server hosting on port 3333
        ServerSocket ss = new ServerSocket(3333);
        Socket s = ss.accept();
        // For sending data onto the socket connection stream
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        //For reading data from the socket connection stream
        DataInputStream dis = new DataInputStream(s.getInputStream());
        //for taking input from user
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        // Remember, server always reads first
        String response = "";
        while(!response.equals("BYE")) {
            response = dis.readUTF();
            System.out.println("Client Says: " + response);
            System.out.println("send message as server:-");
            String sendmsg = br.readLine();
            dos.writeUTF(sendmsg);
        }}}

Here’s a breakdown of the server’s workflow:

  • The server socket listens for incoming client connections.
  • Upon a client’s connection, the server accepts it and establishes input and output streams for communication.
  • The server enters a loop where it continuously reads messages from the client and sends responses until “BYE” is received, indicating the end of the conversation.

Note

you can get its code from GitHub

Setting Up the Client

The client’s role in this chat application is:

  1. Connect to the Server: It connects to the server using the server’s IP address and port number.
  2. Send and Receive Messages: The client sends messages to the server and reads responses from the server. Like the server, it continues this exchange until it sends “BYE”.

Here’s what happens on the client side:

  • The client creates a socket to connect to the server.
  • It sets up input and output streams to communicate with the server.
  • The client starts by sending a message and then waits for a response from the server. This process repeats until the client sends “BYE”.
class Client{
    public void startClient() throws IOException {
        Socket s = new Socket("localhost", 3333);
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        DataInputStream dis = new DataInputStream(s.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String response = "";
        //Client writes first
        while (!response.equals("BYE")){
            System.out.println("send message as Client:-");
            String sendmsg = br.readLine();
            dos.writeUTF(sendmsg);
            response = dis.readUTF();
            System.out.println("Server says: " + response);
        }
    }
}

Chat Application in Java

To bring everything together, our main method creates two threads:

  • Server Thread: This thread starts the server and handles client connections.
  • Client Thread: This thread starts the client and handles sending and receiving messages.

Here’s how to execute the chat application:

  1. Start the Server: The server thread is initiated, and it begins listening for client connections.
  2. Start the Client: The client thread is initiated and connects to the server. You can run the client and server on the same machine for simplicity, using “localhost” as the server address.
  3. Exchange Messages: Once connected, you can type messages on the client, which will be sent to the server, and vice versa.
public class main {

    public static void main(String [] args){

        Thread t1 = new Thread(()->{
            try {
                new Server().startServer();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });

        Thread t2 = new Thread(()->{
            try {
                new Client().startClient();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        t1.start();
        t2.start();
    }
}

Key Takeaways

  • Sockets: Sockets are the foundation of network communication in Java. They provide a way for programs to communicate over a network.
  • Streams: Input and output streams are used to send and receive data between the client and server.
  • Threading: Threads allow the server and client to run concurrently, facilitating real-time communication.

This example illustrates the basics of socket programming and how a simple chat application can be implemented in Java. With these fundamentals, you can build more complex networked applications, adding features like multiple clients, encryption, and more sophisticated protocols.

Source Code of Chat Application

Here is the source code of chat application in java :

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

class Server{

    public void startServer() throws IOException {
        // Start a server hosting on port 3333
        ServerSocket ss = new ServerSocket(3333);
        Socket s = ss.accept();
        // For sending data onto the socket connection stream
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        //For reading data from the socket connection stream
        DataInputStream dis = new DataInputStream(s.getInputStream());
        //for taking input from user
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        // Remember, server always reads first
        String response = "";
        while(!response.equals("BYE")) {
            response = dis.readUTF();
            System.out.println("Client Says: " + response);
            System.out.println("send message as server:-");
            String sendmsg = br.readLine();
            dos.writeUTF(sendmsg);
        }}}
class Client{
    public void startClient() throws IOException {
        Socket s = new Socket("localhost", 3333);
        DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        DataInputStream dis = new DataInputStream(s.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String response = "";
        //Client writes first
        while (!response.equals("BYE")){
            System.out.println("send message as Client:-");
            String sendmsg = br.readLine();
            dos.writeUTF(sendmsg);
            response = dis.readUTF();
            System.out.println("Server says: " + response);
        }
    }
}


public class main {

    public static void main(String [] args){

        Thread t1 = new Thread(()->{
            try {
                new Server().startServer();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });

        Thread t2 = new Thread(()->{
            try {
                new Client().startClient();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        t1.start();
        t2.start();
    }
}

Leave a comment