Socket Programming in Java

Last Updated : 6 Oct, 2026

Socket programming in Java enables communication between two devices over a network by establishing a connection between a client and a server using the java.net package. It forms the foundation for building distributed applications.

  • Uses classes like Socket and ServerSocket to establish communication endpoints.
  • Supports two-way data exchange between client and server.
  • Widely used in applications such as chat systems, file transfer, and client-server architectures.

Client-Side Programming

1. Establish a Socket Connection

To connect to another machine we need a socket connection. A socket connection means both machines know each other’s IP address and TCP port. The java.net.Socket class is used to create a socket.

Socket socket = new Socket(“127.0.0.1”, 5000)

  • The first argument: The IP address of Server i.e. 127.0.0.1  is the IP address of localhost, where code will run on the single stand-alone machine.
  • The second argument: The TCP Port number (Just a number representing which application to run on a server. For example, HTTP runs on port 80. Port number can be from 0 to 65535)

2. Communication 

To exchange data over a socket connection, streams are used for input and output:

  • Input Stream: Reads data coming from the socket.
  • Output Stream: Sends data through the socket.

Example to access these streams:

// to read data
InputStream input = socket.getInputStream();

// to send data
OutputStream output = socket.getOutputStream();

3. Closing the Connection

The socket connection remains open while the client sends multiple messages to the server. When the user enters "Over", the client sends it as the termination message, exits the communication loop, and then closes the socket and associated streams.

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

public class Client {

    private Socket s = null;
    private BufferedReader in = null;
    private DataOutputStream out = null;

    public Client(String addr, int port)
    {

        try {
            // Establish connection
            s = new Socket(addr, port);
            System.out.println("Connected");

            // Read input from terminal
            in = new BufferedReader(
                new InputStreamReader(System.in));

            // Send data to server
            out = new DataOutputStream(s.getOutputStream());

            String m = "";

            // Send messages until "Over" is entered
            while (!m.equals("Over")) {
                m = in.readLine();
                out.writeUTF(m);
            }
        }
        catch (UnknownHostException e) {
            System.out.println(e);
        }
        catch (IOException e) {
            System.out.println(e);
        }
        finally {
            try {
                if (in != null) {
                    in.close();
                }

                if (out != null) {
                    out.close();
                }

                if (s != null) {
                    s.close();
                }
            }
            catch (IOException e) {
                System.out.println(e);
            }
        }
    }

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

Output:

Connected

Server-Side Programming

1. Establish a Socket Connection

To create a server application two sockets are needed. 

  • ServerSocket: This socket waits for incoming client requests. It listens for connections on a specific port.
  • Socket: Once a connection is established, the server uses this socket to communicate with the client.

2. Communication

  • Once the connection is established, you can send and receive data through the socket using streams.
  • The getOutputStream() method is used to send data to the client.

3. Close the Connection 

Once communication is finished, it's important to close the socket and the input/output streams to free up resources.

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

public class Server {
  
    // Initialize socket and input stream
    private Socket s = null;
    private ServerSocket ss = null;
    private DataInputStream in = null;

    // Constructor with port
    public Server(int port) {
      
        // Starts server and waits for a connection
        try
        {
            ss = new ServerSocket(port);
            System.out.println("Server started");

            System.out.println("Waiting for a client ...");

            s = ss.accept();
            System.out.println("Client accepted");

            // Takes input from the client socket
            in = new DataInputStream(
                new BufferedInputStream(s.getInputStream()));

            String m = "";

            // Reads message from client until "Over" is sent
            while (!m.equals("Over"))
            {
                try
                {
                    m = in.readUTF();
                    System.out.println(m);

                }
                catch(IOException i)
                {
                    System.out.println(i);
                }
            }
            System.out.println("Closing connection");

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

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

Explanation: In the above example, we have implemented a server that listens on a specific port, accepts a client connection, and reads messages sent by the client. The server displays the messages until "Over" is received, after which it closes the connection and terminates.

Important Points:

  • Create a ServerSocket on a specific port (e.g., 5000) to listen for client connections.
  • Use accept() to wait for a client; this method blocks until a client connects.
  • Obtain the input stream using getInputStream() to read messages from the client.
  • Continue reading messages until a termination signal (e.g., "Over") is received.
  • Close the client Socket and input stream to terminate the connection.

Run the Application

Open two windows one for Server and another for Client.

1. Run the Server

First run the Server application as:

$ java Server

Output:

Server started 
Waiting for a client ...

2. Run the Client

Then run the Client application on another terminal as

$ java Client

Output:

Connected

3. Exchange Messages

  • Type messages in the Client window.
  • Messages will appear in the Server window.
  • Type "Over" to close the connection.

Here is a sample interaction:

Client:

Hello
I made my first socket connection
Over

Server:

Hello
I made my first socket connection
Over
Closing connection

When the client sends "Over", both programs exit their message-processing loops. The client and server then close their associated streams and sockets, ending the connection.

Note : If you're using Eclipse or likes of such:

  • Compile both of them on two different terminals or tabs
  • Run the Server program first
  • Then run the Client program
  • Type messages in the Client Window which will be received and shown by the Server Window simultaneously.
  • Type Over to end.
Comment