Implementing Client–Server Communication in Java Using Sockets (2025 Edition)

Jaskaran SinghJaskaran Singh
5 min read

When I started learning Backend, I was curious about how apps actually talk to each other — like how a chat app sends messages, or how client-server systems really work under the hood.

That’s when I bumped into Socket Programming.

Even though it’s not the hottest topic in 202, it’s a powerful mental model that helped me understand client-server logic, networking, ports, IP addresses, and how systems connect over a network.

If you're someone who’s diving into backend development or just want to build that strong base, this is for you.

Topics Covered:

  • What is Socket Programming?

  • What is a "Socket" in Java?

  • How Client-Server communication works

  • Java Code for both Server and Client

  • How to run & test it yourself (with terminal flow)


What is Socket Programming in Java?

Socket programming is just a way of connecting two programs(nodes) on a network to communicate with each other.

Imagine:

One program (the server) is sitting and waiting for a message,

while the other (the client) walks up to it and says something.

In Java, this is handled using Socket and ServerSocket classes from the java.net package.

It works best with TCP (connection-oriented) communication, which is reliable (used in most apps like browsers, WhatsApp, etc.).


What is a Socket in Java?

A socket is basically:

IP Address + Port Number = Endpoint

It’s like having a personal address(IP Address) and a room number(Post Number) where someone can reach you.

Java makes it really easy to create this kind of endpoint communication using:

  • Socket class → For the client to connect

  • ServerSocket → For the server to wait and accept connections

These help create a simple tunnel for data to flow between programs.


🔧Writing the Client-Side

In case of client-side Logic.

How it works:

  1. The client waits for the server to start.

  2. Once the server is up, the client sends a request.

  3. Then, the client waits for the server’s response.

we’ll go through both client-side and server-side code — both are important to understand how the communication works.

Step 1: Establish Connection

A socket connection tells that the two machines have information about each other’s network location (IP Address) and TCP port.

To connect to a server, we create a socket as:

Socket socket = new Socket("127.0.0.1", 5000);
  • "127.0.0.1" = localhost (your own machine)

  • 5000 = Port number (where server listens) Basically It is a number that represents which application should run on a server.

Step 2. Communication

In order to communicate, Streams are uses DataInputStream and DataOutputStream to send and receive data through the socket.

DataInputStream→ To read input

DataOutputStream→ To send messages

Step 3. Closing the connection

Once the communication is over, we close the streams and socket to free system resources.

Client Side Code

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

public class Client {
    private Socket socket = null;
    private DataInputStream input = null;
    private DataOutputStream out = null;

    // Constructor to connect to server
    public Client(String address, int port) {
        try {
            socket = new Socket(address, port);
            System.out.println("Connected");

            input = new DataInputStream(System.in);
            out = new DataOutputStream(socket.getOutputStream());

            String line = "";
            while (!line.equals("Over")) {
                line = input.readLine();
                out.writeUTF(line);
            }

            // Close connection
            input.close();
            out.close();
            socket.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public static void main(String args[]) {
        new Client("127.0.0.1", 5000);
    }
}

🔧Writing the Server-Side

Now, let’s write the server side logic.

How it works:

  1. The server starts first and waits for a client request.

  2. Once a client connects, the server responds.

  3. The server reads data sent from the client.

Step 1: Start and Wait

To code the server-side application, you need two sockets:

  • ServerSocket: Waits for and accepts incoming client connections.

  • Socket: Handles communication once the connection is accepted.

ServerSocket server = new ServerSocket(5000);
Socket socket = server.accept();

The server waits until a client connects. Once that happens, the connection is established.

Step 2: Receive Messages

Use input streams to read what the client sends.

// To read data:
socket.getInputStream();
// To send data:
socket.getOutputStream();

Close the Connection

Always close Sockets and Streams once done.

Server Side Code

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

public class Server {
    private Socket socket = null;
    private ServerSocket server = null;
    private DataInputStream in = null;

    // Constructor to start server and accept client
    public Server(int port) {
        try {
            server = new ServerSocket(port);
            System.out.println("Server started. Waiting for a client ...");

            socket = server.accept();
            System.out.println("Client accepted");

            in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

            String line = "";
            while (!line.equals("Over")) {
                line = in.readUTF();
                System.out.println("Client: " + line);
            }

            System.out.println("Closing connection");

            // Close connections
            socket.close();
            in.close();
        } catch (IOException i) {
            System.out.println(i);
        }
    }

    public static void main(String args[]) {
        new Server(5000);
    }
}

🔧Execution Flow:

Step 1: Run the Server First

First, run the Server.java file. As soon as it started, it printed:

> javac Server.java
> java Server
Server started. Waiting for a client ...

This means your server is now patiently waiting for someone to talk.

Step 2: Run the Client and Connect

Next, run the Client.java file. Instantly, the client printed:

> javac Client.java
> java Client
Connected

That’s the confirmation that the client successfully reached the server.

Now, you can type messages:

Hello Server!
How are you?
Over

Server Receives and Displays the Messages

Client: Hello Server!
Client: How are you?

And finally:

Closing connection

You can run both server and client programs using a terminal or command prompt, but using an IDE like Eclipse/Intellij makes it easier to manage and execute your code.

Final Thoughts

Even though technologies like REST API,s and Microservices are dominating in 2025, understanding raw socket communication gives you superpowers — especially if you want to:

  • Build custom protocols

  • Understand how real-time systems (like chat, multiplayer games) work

I wrote this not just to teach, but to document my learning in a clear way.

If you're learning backend or Java,

you should try building this once — it's worth it.

My next blog will dive into something much more common and widely used in modern backend systems — REST APIs. So Stay tuned

Thanks for reading.

Keep Building

— J.K. Malra


1
Subscribe to my newsletter

Read articles from Jaskaran Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jaskaran Singh
Jaskaran Singh

I build reliable backend systems using Java, Spring Boot, and cloud technologies like AWS. Currently pursuing MCA and a strong drive to grow, I’m currently focused on mastering cloud infrastructure, backend development, and data structures. I’m also building a streak-based productivity app to showcase my technical skills and problem-solving mindset. My long-term goal is to developer cloud and backend solutions that are clean, scalable, and impactful. Always learning. Always building. Open to collaboration and new ideas.