Java Advanced Topics and Techniques

Socket Programming in Java: Comprehensive Guide

Socket Programming in Java: Comprehensive Guide

What is Socket Programming in Java?

Through socket programming, Java applications running on different JREs can communicate with each other. The socket programming method allows two nodes to communicate over a network.

In a client-server connection, the server forms the listener socket, and the client contacts the server. One Socket listens on a particular IP port while the other reaches out to the other.

It would help if you used the Socket and Server Socket classes to program sockets using connection-oriented methods.

Let us now understand Socket Programming's core concept, a socket.

What is a Socket in Java?

There is a class, Socket, in the Java platform that implements one side of a two-way network connection between your Java program and another program using a TCP protocol.

In other words, Java sockets are two-way communication links between programs running on the network.

The TCP protocol uses port numbers to identify which application should receive data from a socket. Programmers can use the Java Socket programming language to program in either a connection-oriented or a connection-less mode.

Socket or ServerSocket classes are used in connection-oriented socket programming, while in connection-less socket programming, you can use DatagramSocket or DatagramPacket classes.

Clients must provide two pieces of information to Socket programming to establish a successful connection:

  • IP Address of Server
  • Port number.

Example of Socket Programming

Here, we will communicate one way between the client and server.  This application sends a message from the client to the server, which reads and prints the message.

Since we are running a connection-oriented program, we are using two classes of sockets: Socket and ServerSocket.  

A ServerSocket class runs on the application's server side to read and write messages. ServerSocket's accept() method blocks console access until the client connects. When the client connects successfully, the server returns an instance of Socket.

Creating Server

Our server application requires an instance of the ServerSocket class. To communicate between the server and the client, we are using port 6666. Alternatively, you can choose any other port number.  Accept() returns a Socket instance when clients connect using the given port number.

Creating Client

We need to create an instance of Socket for the client application. In this case, we must pass the IP address or hostname of the server, along with the port number. Since our server runs on the same system, we're using "localhost.".

A code example of Java socket programming will show how a client sends a message to a server, which then prints the message to the client

SocketServerExample.java

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServerExample {
   
    private static ServerSocket server;
    private static int port = 6666;
   
    public static void main(String args[]) throws IOException, ClassNotFoundException{
        server = new ServerSocket(port);
        while(true){
            System.out.println("Waiting for the client request");
            Socket socket = server.accept();
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            String message = (String) ois.readObject();
            System.out.println("Message Received: " + message);
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject("Hi Client "+message);
            ois.close();
            oos.close();
            socket.close();
            if(message.equalsIgnoreCase("exit")) break;
        }
        System.out.println("Shutting down Socket server!!");
        server.close();
    }   
}

SocketClientExample.java

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketClientExample {

    public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException{
        InetAddress host = InetAddress.getLocalHost();
        Socket socket = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        for(int i=0; i<5;i++){
            socket = new Socket(host.getHostName(), 9876);
            oos = new ObjectOutputStream(socket.getOutputStream());
            System.out.println("Sending request to Socket Server");
            if(i==4)oos.writeObject("exit");
            else oos.writeObject(""+i);
            ois = new ObjectInputStream(socket.getInputStream());
            String message = (String) ois.readObject();
            System.out.println("Message: " + message);
            ois.close();
            oos.close();
            Thread.sleep(100);
        }
    }
}

Output

java SocketServerExample.java
Waiting for the client request
Message Received: 0
Waiting for the client request
Message Received: 1
Waiting for the client request
Message Received: 2
Waiting for the client request
Message Received: 3
Waiting for the client request
Message Received: exit
Shutting down Socket server!!


java SocketClientExample.java
Sending request to Socket Server
Message: Hi Client 0
Sending request to Socket Server
Message: Hi Client 1
Sending request to Socket Server
Message: Hi Client 2
Sending request to Socket Server
Message: Hi Client 3
Sending request to Socket Server
Message: Hi Client exit

write your code here: Coding Playground