Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

TCP/IP Server Sockets and Datagram (UDP) Programming

Lesson 37 of 46 in the free Web Technologies notes on Siksha Sarovar, written by Rohit Jangra.

TCP/IP Server Sockets and Datagram (UDP) Programming

TCP/IP Server Sockets

A ServerSocket listens on a port and accepts incoming client connections. Each accepted connection returns a regular Socket used to communicate with that specific client.

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(5000);
        System.out.println("Server listening on port 5000...");

        while (true) {
            Socket clientSocket = serverSocket.accept(); // blocks until a client connects
            System.out.println("Client connected: " + clientSocket.getInetAddress());

            BufferedReader in = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream()));
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

            String message = in.readLine();
            System.out.println("Received: " + message);
            out.println("Echo: " + message);

            clientSocket.close();
        }
    }
}

Key ServerSocket Methods

MethodPurpose
accept()Blocks until a client connects, returns a Socket
getLocalPort()Port the server is bound to
close()Stops listening
setSoTimeout(int ms)Timeout for accept()

Concurrent Servers with Threads

A single-threaded server handles one client at a time. Spawning a thread per client allows concurrent connections:

while (true) {
    Socket clientSocket = serverSocket.accept();
    new Thread(() -> handleClient(clientSocket)).start();
}

Datagram (UDP) Programming

UDP (User Datagram Protocol) is connectionless and unreliable but fast — no handshake, no guaranteed delivery or order. Java represents UDP communication with DatagramSocket and DatagramPacket.

UDP Client

import java.net.*;

public class UDPClient {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket();
        byte[] message = "Hello UDP Server".getBytes();

        InetAddress serverAddr = InetAddress.getByName("localhost");
        DatagramPacket packet = new DatagramPacket(message, message.length, serverAddr, 6000);
        socket.send(packet);

        socket.close();
    }
}

UDP Server

import java.net.*;

public class UDPServer {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(6000);
        byte[] buffer = new byte[1024];

        while (true) {
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            socket.receive(packet); // blocks until a packet arrives

            String received = new String(packet.getData(), 0, packet.getLength());
            System.out.println("Received: " + received + " from " + packet.getAddress());
        }
    }
}

TCP vs UDP

FeatureTCP (Socket/ServerSocket)UDP (DatagramSocket/DatagramPacket)
ConnectionConnection-oriented (3-way handshake)Connectionless
ReliabilityGuaranteed delivery, orderedNo guarantee, may lose/reorder packets
SpeedSlower (overhead)Faster (minimal overhead)
Use caseWeb, email, file transferStreaming, gaming, DNS, VoIP
Java classesSocket, ServerSocketDatagramSocket, DatagramPacket
Key Takeaway: ServerSocket.accept() blocks until a TCP client connects, and threading lets a server handle many clients concurrently. UDP trades reliability for speed — DatagramSocket sends/receives self-contained DatagramPackets with no connection setup.