A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/socket-programming-in-java/ below:

Socket Programming in Java - GeeksforGeeks

Socket Programming in Java

Last Updated : 23 Jul, 2025

Socket programming in Java allows different programs to communicate with each other over a network, whether they are running on the same machine or different ones. This article describes a very basic one-way Client and Server setup, where a Client connects, sends messages to the server and the server shows them using a socket connection. There is a lot of low-level stuff that needs to happen for these things to work but the Java API networking package (java.net) takes care of all of that, making network programming very easy for programmers.

Note: A "socket" is an endpoint for sending and receiving data across a network.

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)

2. Communication 

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

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 is closed explicitly once the message to the server is sent.

Example: Here, in the below program the Client keeps reading input from a user and sends it to the server until “Over” is typed.

Java
// Demonstrating Client-side Programming
import java.io.*;
import java.net.*;

public class Client {
  
    // Initialize socket and input/output streams
    private Socket s = null;
    private DataInputStream in = null;
    private DataOutputStream out = null;

    // Constructor to put IP address and port
    public Client(String addr, int port)
    {
        // Establish a connection
        try {
            s = new Socket(addr, port);
            System.out.println("Connected");

            // Takes input from terminal
            in = new DataInputStream(System.in);

            // Sends output to the socket
            out = new DataOutputStream(s.getOutputStream());
        }
        catch (UnknownHostException u) {
            System.out.println(u);
            return;
        }
        catch (IOException i) {
            System.out.println(i);
            return;
        }

        // String to read message from input
        String m = "";

        // Keep reading until "Over" is input
        while (!m.equals("Over")) {
            try {
                m = in.readLine();
                out.writeUTF(m);
            }
            catch (IOException i) {
                System.out.println(i);
            }
        }

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

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

Output
java.net.ConnectException: Connection refused (Connection refused)

Explanation: In the above example, we have created a client program that establishes a socket connection to a server using an IP address and port, enabling data exchange. The client reads messages from the user and sends them to the server until the message "Over" is entered, after which the connection is closed.

Server-Side Programming 1. Establish a Socket Connection

To create a server application two sockets are needed. 

2. Communication 3. Close the Connection 

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

Example: The below Java program demonstrate the server-side programming

Java
// Demonstrating Server-side Programming
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:

socket = server.accept()

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

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

Notice that sending “Over” closes the connection between the Client and the Server just like said before. 

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

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


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4