TCP/IP Socket Programming & UDP Datagram Programming in Java
1. Two Types of Socket Programming in Java
Java’s java.net package supports two distinct models of network communication between a Client and a Server:
- TCP/IP Socket Programming (Connection-Oriented): Uses
SocketandServerSocketclasses. - UDP Datagram Programming (Connectionless): Uses
DatagramSocketandDatagramPacketclasses.
2. TCP/IP Socket Programming (Socket & ServerSocket)
TCP/IP (Transmission Control Protocol / Internet Protocol) is a connection-oriented, reliable, two-way stream protocol. Before sending any data, the Client and Server establish a dedicated virtual connection (like a telephone call). Data is guaranteed to arrive in the exact order it was sent.
Figure 4.5: How TCP/IP Client-Server Socket Communication Works
1. ServerSocket(5000)Server opens port 5000 & waits at
accept()← Connection Request ←
2. Socket("localhost", 5000)Client requests connection to Server IP & Port
↔ Two-Way Streams ↔
3. InputStream / OutputStreamBoth exchange messages & call
close()A. The ServerSocket Class (For the Server)
- Used by the Server program to listen for incoming client connection requests on a specific port number.
- Constructor:
ServerSocket ss = new ServerSocket(int portNumber); - Key Method —
Socket accept(): Waits (blocks) until a client connects to that port, and once connected, returns a normalSocketobject to communicate with that client!
B. The Socket Class (For the Client)
- Used by the Client program to initiate a connection with the Server using the Server’s IP address/hostname and Port number.
- Constructor:
Socket s = new Socket(String hostName, int portNumber); - Key Methods:
InputStream getInputStream(): Reads data sent by the other side.OutputStream getOutputStream(): Sends data to the other side.void close(): Closes the socket connection.
Complete Working TCP Client-Server Program (Exam Favorite!)
Program 1: TCP Server (MyServer.java)
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) {
try {
// 1. Create ServerSocket listening on port 5000
ServerSocket ss = new ServerSocket(5000);
System.out.println("Server started! Waiting for a client on port 5000...");
// 2. Wait for client connection and accept it
Socket s = ss.accept();
System.out.println("Client connected!");
// 3. Read message sent by the Client
DataInputStream dis = new DataInputStream(s.getInputStream());
String message = dis.readUTF();
System.out.println("Message from Client: " + message);
// 4. Close streams and sockets
dis.close();
s.close();
ss.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Program 2: TCP Client (MyClient.java)
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try {
// 1. Connect to Server running on "localhost" (127.0.0.1) at port 5000
Socket s = new Socket("localhost", 5000);
// 2. Send a message to the Server using OutputStream
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF("Hello Server! Greetings from BCA DAVV Student!");
dos.flush();
// 3. Close stream and socket
dos.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
3. UDP Datagram Programming (DatagramSocket & DatagramPacket)
What is a Datagram? A Datagram is an independent, self-contained bundle (packet) of data sent over a network using UDP (User Datagram Protocol) without establishing any prior connection between the sender and receiver.
Simple Real-Life Analogy:
- TCP Socket is like a Phone Call (you dial, wait for the other person to pick up
accept(), talk over a dedicated line, and hang upclose()).- UDP Datagram is like dropping a Letter / Postcard in a Post Box! Every envelope (
DatagramPacket) has the receiver’s full IP address and port written on it, and the Post Office (DatagramSocket) shoots it across the network without checking if the receiver is ready!
Two Core Classes for Datagram Programming:
DatagramPacket(The Envelope + Data Letter): Holds the byte array of data to be sent or received, along with its length, destinationInetAddress, and destination port number.- Constructor for Sending:
DatagramPacket(byte[] buf, int length, InetAddress ip, int port) - Constructor for Receiving:
DatagramPacket(byte[] buf, int length)
- Constructor for Sending:
DatagramSocket(The Post Box / Courier): The mechanism used to actuallysend(packet)andreceive(packet)datagram packets across the network.
Complete Working UDP Datagram Sender & Receiver Program
Program 1: UDP Sender (DatagramSender.java)
import java.net.*;
public class DatagramSender {
public static void main(String[] args) throws Exception {
// 1. Create a DatagramSocket (Post Box)
DatagramSocket ds = new DatagramSocket();
// 2. Prepare message bytes and destination IP address
String msg = "Welcome to UDP Datagram Programming in Java!";
byte[] buffer = msg.getBytes();
InetAddress receiverIP = InetAddress.getByName("127.0.0.1");
// 3. Pack data + destination IP + destination port (3000) into DatagramPacket
DatagramPacket dp = new DatagramPacket(buffer, buffer.length, receiverIP, 3000);
// 4. Send the packet and close socket
ds.send(dp);
System.out.println("Datagram packet sent successfully!");
ds.close();
}
}
Program 2: UDP Receiver (DatagramReceiver.java)
import java.net.*;
public class DatagramReceiver {
public static void main(String[] args) throws Exception {
// 1. Open DatagramSocket listening on port 3000
DatagramSocket ds = new DatagramSocket(3000);
byte[] buffer = new byte[1024];
// 2. Create empty DatagramPacket to receive incoming data
DatagramPacket dp = new DatagramPacket(buffer, 1024);
System.out.println("Waiting to receive UDP packet on port 3000...");
// 3. Receive packet and convert bytes back to String
ds.receive(dp);
String receivedMsg = new String(dp.getData(), 0, dp.getLength());
System.out.println("Received Message: " + receivedMsg);
ds.close();
}
}
4. Comparison: TCP/IP Socket vs UDP Datagram Programming
| Basis | TCP/IP Socket Programming | UDP Datagram Programming |
|---|---|---|
| 1. Protocol Used | TCP (Transmission Control Protocol). | UDP (User Datagram Protocol). |
| 2. Connection Type | Connection-Oriented (Dedicated virtual circuit via accept()). |
Connectionless (No prior handshake; packets sent independently). |
| 3. Java Classes Used | Socket and ServerSocket. |
DatagramSocket and DatagramPacket. |
| 4. Reliability & Order | 100% Reliable; guarantees zero data loss and preserves exact order. | Unreliable (Best-Effort); packets may arrive out of order or be dropped. |
| 5. Speed & Overhead | Slightly slower due to connection setup, acknowledgments, and error checking. | Very fast with minimal overhead. |
| 6. Best Real-Life Use Case | Banking transactions, File transfers (FTP), Web browsing (HTTP/HTTPS), Chat apps. | Live video streaming, Online multiplayer gaming, DNS lookups, VoIP calls. |
💡 Exam Preparation Tips for DAVV BCA
- This topic frequently appears as an 8-mark question: “Explain TCP/IP Socket programming vs Datagram programming in Java with suitable code.”
- Always clearly state the two pairs of classes:
- TCP/IP:
Socket+ServerSocket(usesgetInputStream()/getOutputStream()) - UDP Datagram:
DatagramSocket+DatagramPacket(usesds.send(dp)/ds.receive(dp))
- TCP/IP: