Table of contents
1.
Introduction
2.
Java Socket Programming
3.
Importance of Socket Programming in Java
4.
Socket Class
4.1.
Important Methods
5.
ServerSocket Class
5.1.
Important Methods
6.
Examples of Socket Programming
6.1.
Java Socket Programming Example (Read-Write both sides)
7.
Practical Use Cases of Socket Programming
8.
Real-World Applications of Socket Programming
9.
Frequently Asked Questions
9.1.
What is socket programming in java?
9.2.
Which protocol do sockets use?
9.3.
What are the advantages of socket programming?
9.4.
Is socket A process?
9.5.
What are the Disadvantages of Java sockets?
10.
Conclusion
Last Updated: Jun 9, 2025
Medium

Socket Programming in Java

Author Sanjana Yadav
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Java, socket programming is used to communicate across programs running on different JREs. It might be connection-oriented or non-connection-oriented. A socket, in general, is a method of establishing a connection between a client and a server.

 Socket Programming in Java

Java Socket Programming

Sockets provide a means of communication between two machines using TCP. At its end of the conversation, a client application builds a socket and attempts to connect it to a server.

The server produces a socket object when the connection is established. Writing to and reading from the socket allows the client and server to interact.

When the connection is established, the server produces a socket object on its end of the conversation. The client and server can now exchange information by writing to and reading from the socket.

The java.net.Socket class represents a socket. The java.net.ServerSocket class gives the server program a way to listen to clients and connect with them.

Following are the steps to establish a TCP connection between two computers using sockets-

  1. The server creates a ServerSocket object, which provides the port number for communication.
  2. The server calls the accept() function of the ServerSocket class. This method waits for a client to connect to the server on the specified port before returning.
  3. After the server has been waiting, a client creates a Socket object, providing the server name and port number to connect to.
  4. The Socket class's constructor tries to connect the client to the provided server and port number. If communication is established, the client is now in possession of a Socket object that may communicate with the server.
  5. The accept() method on the server-side returns a reference to a new socket on the server connected to the client's socket.
Socket API

After the connections have been established, communication can occur via I/O streams. Each socket has an OutputStream as well as an InputStream. The client's OutputStream is linked to the server's InputStream, and the server's OutputStream is linked to the client's InputStream.

Because TCP is a two-way communication protocol, data may be transferred in both directions simultaneously.

Importance of Socket Programming in Java

Socket programming is essential in Java for building networked applications that require real-time communication, data exchange, and distributed processing. Java provides robust support for socket programming through its built-in java.net package, which simplifies the creation of both client-server and peer-to-peer applications. With classes like Socket, ServerSocket, and DatagramSocket, developers can easily establish TCP and UDP connections to enable reliable or fast, connectionless data transmission.

Socket programming in Java is widely used in web servers, chat applications, multiplayer games, file-sharing systems, and distributed databases, where seamless and efficient communication between multiple devices or systems is crucial. Java’s platform independence ensures that socket-based applications can run across different operating systems without modification, making it highly practical for cross-platform networking solutions.

Socket Class

A socket is just a communication endpoint between machines. To construct a socket, use the Socket class.

Important Methods

Method

Description

public InputStream getInputStream()returns the InputStream attached with this socket.
public OutputStream getOutputStream()returns the OutputStream attached with this socket.
public synchronized void close()closes this socket

ServerSocket Class

A server socket may be created using the ServerSocket class. This object is used to communicate with the clients.

Important Methods

Method

Description

public Socket accept()returns the socket and establishes a connection between server and client.
public synchronized void close()closes the server socket.

Examples of Socket Programming

Creating Server:

To build the server application, we must first construct an instance of the ServerSocket class. Port number 6666 is used for communication between the client and server in this case. You can also select another port number. The accept() function sits back and waits for the client. If a client connects to the supplied port number, it returns a Socket instance.

ServerSocket newssoc=new ServerSocket(6666);  
Socket soc=newssoc.accept();//establishes a connection and waits for the client 
  

Creating Client:

To build the client application, we must first construct an instance of the Socket class. The IP address or hostname of the server and a port number must be passed here. Because our server is operating on the same machine, we're using "localhost" here.

Socket newsoc=new Socket("localhost",6666);  

Let's look at a simple Java socket programming example in which the client transmits a text and the server receives and outputs it. Also, try it on online java compiler.

Server-side:

import java.io.*;
import java.net.*;
public class server {
    public static void main(String[] args) {
        try {
            ServerSocket ssoc = new ServerSocket(6666);
            Socket soc = ssoc.accept();// establishes connection
            DataInputStream dis = new DataInputStream(soc.getInputStream());
            String str = (String) dis.readUTF();
            System.out.println("message= " + str);
            ssoc.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Client-side:

import java.io.*;
import java.net.*;
public class client {
    public static void main(String[] args) {
        try {
            Socket soc = new Socket("localhost", 6666);
            DataOutputStream dout = new DataOutputStream(soc.getOutputStream());
            dout.writeUTF("Hello Server");
            dout.flush();
            dout.close();
            soc.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}  

To run this program, open two command prompts and run both programs simultaneously. Following the execution of the client application, a message will be shown on the server console.

Java Socket Programming Example (Read-Write both sides)

In this example, the client will first write to the server, after which the server will receive and output the text. The server will then send a message to the client, which will receive and print the text. The process continues.

Server-side:

import java.net.*;
import java.io.*;
class server {
    public static void main(String args[]) throws Exception {
        ServerSocket ssoc = new ServerSocket(3333);
        Socket soc = ssoc.accept();
        DataInputStream din = new DataInputStream(soc.getInputStream());
        DataOutputStream dout = new DataOutputStream(soc.getOutputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = "", str2 = "";
        while (!str.equals("stop")) {
            str = din.readUTF();
            System.out.println("client says: " + str);
            str2 = br.readLine();
            dout.writeUTF(str2);
            dout.flush();
        }
        din.close();
        soc.close();
        ssoc.close();
    }
}

Client-side:

import java.net.*;
import java.io.*;
class client {
    public static void main(String args[]) throws Exception {
        Socket soc = new Socket("localhost", 3333);
        DataInputStream din = new DataInputStream(soc.getInputStream());
        DataOutputStream dout = new DataOutputStream(soc.getOutputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = "", str2 = "";
        while (!str.equals("stop")) {
            str = br.readLine();
            dout.writeUTF(str);
            dout.flush();
            str2 = din.readUTF();
            System.out.println("Server says: " + str2);
        }
        dout.close();
        soc.close();
    }
}


Also see, Duck Number in Java and Hashcode Method in Java

Practical Use Cases of Socket Programming

Socket programming is widely used in various real-world scenarios where continuous, real-time data exchange is required between devices or applications.

  • Real-Time Messaging Apps:
    Applications like WhatsApp and Slack use socket programming to establish real-time communication channels between users. When a user sends a message, the socket ensures instant delivery to the recipient without delays, enabling seamless chat experiences.
  • Multiplayer Games:
    Online multiplayer games rely on sockets to keep all players connected in real-time. For example, when a player moves or performs an action, the update is immediately sent to other players using socket-based communication, ensuring synchronized gameplay.
  • File Transfer Protocols:
    Applications like FTP clients and peer-to-peer file-sharing platforms use sockets to enable direct file transfer between machines over a network. This allows users to upload or download files efficiently across the internet.
  • Remote Server Communication:
    Socket programming is fundamental in developing client-server models, such as web servers and database servers. For instance, when a browser requests a webpage, a socket is used to establish a connection and transfer the requested data from the server to the client.

These use cases demonstrate how sockets facilitate fast, reliable, and continuous data exchange in modern applications.

Real-World Applications of Socket Programming

Several industries and technologies depend heavily on socket programming to maintain real-time connectivity and seamless communication.

  • Telecommunications:
    Voice over IP (VoIP) services and call management systems use sockets to transmit audio data and manage live calls over the internet with minimal delay.
  • Online Gaming:
    Multiplayer online games like PUBG and Fortnite use sockets to manage real-time player movements, game events, and synchronization across servers and player devices.
  • Chat Applications:
    Messaging platforms such as Facebook Messenger and Microsoft Teams rely on socket programming to instantly deliver text, voice, and video messages between users worldwide.
  • Internet of Things (IoT):
    IoT devices like smart home systems and wearable fitness trackers use sockets to constantly send and receive data to and from centralized servers, enabling real-time monitoring and control.
  • In all these applications, socket programming ensures reliable, low-latency communication that is essential for smooth user experiences and system performance.

Frequently Asked Questions

What is socket programming in java?

In Java, socket programming is used to communicate across programs running on different JREs. It might be connected-oriented or connectionless. A socket, in general, is a method of establishing a connection between a client and a server.

Which protocol do sockets use?

Transmission Control Protocol (TCP), Stream Control Transmission Protocol (SCTP), or Datagram Congestion Control Protocol (DCCP) connection-oriented sockets (DCCP).

What are the advantages of socket programming?

Allows for flexible access to files and data via a network, Pooling resources, Security, Speed, Software administration is centralized, Provides protection like sending sensitive (password-protected) information and applications via a network.

Is socket A process?

A socket allows two processes on the same computer or on different systems to connect with one another. A socket serves as an inter-process communicator and is regarded as the process communication's terminus. The socket communicates via a file descriptor and is commonly used in client-server applications.

What are the Disadvantages of Java sockets?

Socket-based communication only allows for the transmission of raw data packets between apps. Both the client and the server must provide tools to make the data values in some way.

Conclusion

  • Cheers if you reached here! In this blog, we learned about Socket programming in Java.
  • We have covered the Socket and the ServerSocket classes and their uses.
  • We have also seen different methods inside Socket and ServerSocket classes and their uses.
  • Further, we saw examples of socket programming in java.
     

On the other hand, learning never ceases, and there is always more to learn. So, keep learning and keep growing, ninjas!

Check out the Computer Networks to know more about computer networking.

Good luck with your preparation!

Live masterclass