Network ProgrammingUnit 610 min read
Multicast & Datagram Sockets: UDP, Multicasting, and Non-blocking I/O
Unit 6 of Network Programming: Explores connectionless UDP sockets, multicast communication, datagram handling, and non-blocking I/O in Java, with practical examples, code traces, and real-world applications like live streaming and IoT messaging.
TAKEAWAYS
- UDP Sockets are connectionless, lightweight, and used for speed-critical apps (e.g., VoIP, live video) but lack reliability guarantees.
- Multicast Groups enable one-to-many communication (e.g., live sports feeds, stock price updates) via IP addresses like
239.0.0.0–239.255.255.255. - Datagrams are fixed-size packets (e.g., DNS queries) with no reassembly; UDP uses them for efficiency.
- Non-blocking I/O improves performance by allowing threads to handle multiple sockets concurrently (e.g., web servers).
- Java’s
DatagramSocketandMulticastSocketclasses simplify UDP/multicast programming with methods likesend(),receive(), andjoinGroup(). - Real-world use: Pathao’s ride-sharing updates (UDP broadcasts), Daraz’s inventory alerts (multicast), and NTC’s network diagnostics (non-blocking I/O).
1. Connectionless vs. Connection-Oriented Sockets
UDP (User Datagram Protocol) sockets are connectionless, meaning they don’t establish a handshake like TCP. Instead, they send datagrams (small, independent packets) directly to the destination. This makes UDP faster but unreliable (no retransmission, no flow control).
Key Differences: TCP vs. UDP
| Feature | TCP (Connection-Oriented) | UDP (Connectionless) |
|---|---|---|
| Connection | Requires SYN, ACK handshake |
No connection; fire-and-forget |
| Reliability | Guaranteed delivery (ACKs) | No retransmission; may lose data |
| Ordering | Packets arrive in order | Packets may arrive out of order |
| Overhead | High (headers, sequence numbers) | Low (64 bytes vs. 20 bytes) |
| Use Cases | Files, emails, HTTP | VoIP, live video, IoT |
| TCP Handshake (3-Way) | UDP Datagram (No Handshake) |
|---|---|
2. Datagram Sockets in Java
Java’s DatagramSocket class enables UDP communication. Unlike TCP’s streams, UDP sends datagrams (fixed-size packets) to a specific host and port.
How Datagrams Work
- Sender creates a
DatagramPacketwith data and destination. - Receiver listens on a port and extracts data from incoming packets.
- No connection: Each packet is independent.
Example: UDP Echo Server/Client
Code: UDP Echo Server
import java.net.*;
public class UDPServer {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(9876);
byte[] buffer = new byte[1024];
while (true) {
DatagramPacket request = new DatagramPacket(buffer, buffer.length);
socket.receive(request); // Blocks until data arrives
String received = new String(request.getData(), 0, request.getLength());
System.out.println("Received: " + received);
DatagramPacket response = new DatagramPacket(
received.getBytes(),
received.getBytes().length,
request.getAddress(),
request.getPort()
);
socket.send(response);
}
}
}
Code: UDP Echo Client
import java.net.*;
public class UDPClient {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
String message = "Hello UDP!";
byte[] buffer = message.getBytes();
DatagramPacket packet = new DatagramPacket(
buffer, buffer.length, "localhost", 9876
);
socket.send(packet);
byte[] replyBuffer = new byte[1024];
DatagramPacket reply = new DatagramPacket(replyBuffer, replyBuffer.length);
socket.receive(reply);
System.out.println("Server says: " + new String(reply.getData(), 0, reply.getLength()));
socket.close();
}
}
Trace Table: UDP Echo Client Execution
| Step | Action | DatagramPacket Details |
|---|---|---|
| 1 | Send "Hello UDP!" | buffer = "Hello UDP!", port = 9876 |
| 2 | Receive server reply | reply.getData() = "Hello UDP!" (echoed) |
Visual: UDP Packet Flow
sequenceDiagram
participant Client
participant Server
Client->>Server: DatagramPacket("Hello UDP!", 9876)
Server-->>Client: DatagramPacket("Hello UDP!", 9876)
note right of Client: `buffer = "Hello UDP!", port = 9876`
note right of Server: `reply.getData() = "Hello UDP!"`3. Multicast Communication
Multicast sends data from one sender to many receivers using a multicast group address (e.g., 239.255.0.1). Unlike broadcast (which floods all hosts), multicast is efficient and scalable.
How Multicast Works
- Sender joins a multicast group (e.g.,
239.0.0.5). - Router forwards packets only to networks with interested receivers.
- Receivers explicitly join the group using
joinGroup().
Java’s MulticastSocket
- Extends
DatagramSocketwith multicast-specific methods:joinGroup(MulticastSocket): Join a group.leaveGroup(MulticastSocket): Leave a group.send(DatagramPacket): Send to multicast address.
Example: Multicast Chat
Sender Code:
MulticastSocket socket = new MulticastSocket();
InetAddress group = InetAddress.getByName("239.255.0.1");
socket.joinGroup(group);
String message = "Multicast message!";
DatagramPacket packet = new DatagramPacket(
message.getBytes(), message.getBytes().length, group, 9876
);
socket.send(packet);
Receiver Code:
MulticastSocket socket = new MulticastSocket(9876);
socket.joinGroup(InetAddress.getByName("239.255.0.1"));
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
System.out.println("Received: " + new String(packet.getData()));
Visual: Multicast Group Membership
graph TD A["Sender"] -->|"Sends to 239.255.0.1:9876"| B["Multicast Router"] B --> C["Receiver 1"] B --> D["Receiver 2"] B --> E["Receiver 3"]
4. Non-Blocking I/O vs. Blocking I/O
- Blocking I/O: Default in Java. A thread waits (
socket.receive()) until data arrives. - Non-blocking I/O: Thread continues executing while waiting for data (e.g., using
select()orepoll).
Advantages of Non-Blocking I/O
| Feature | Blocking I/O | Non-Blocking I/O |
|---|---|---|
| Thread Usage | One thread per socket | One thread handles many sockets |
| Performance | Poor for high concurrency | Scales with many connections |
| Use Case | Simple clients | Web servers, chat apps |
| Blocking I/O (Single Thread) | Non-Blocking I/O (Thread Pool) |
|---|---|
![]() |
![]() |
5. Real-World Applications
In the Real World
Pathao Ride Updates
- Idea: UDP multicast sends real-time ride status (e.g., "Your driver is 2 mins away") to all Pathao users subscribed to a group.
- Why UDP? Low latency; drivers don’t need to wait for acknowledgments.
Daraz Inventory Alerts
- Idea: When a product (e.g., "Nepalgunj Rice") restocks, Daraz sends a multicast packet to all users tracking that item.
- Why Multicast? Efficiently reaches thousands of users without flooding the network.
NTC Network Diagnostics
- Idea: NTC uses non-blocking I/O in its monitoring tools to check network health across multiple routers simultaneously.
- Why Non-Blocking? Handles thousands of ping requests without crashing.
6. Worked Example: UDP Port Scanner
Task: Scan local UDP ports 1024–2024 for open services.
Code: UDP Port Scanner
import java.net.*;
public class UDPScanner {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
socket.setSoTimeout(1000); // Timeout after 1 second
for (int port = 1024; port <= 2024; port++) {
try {
socket.connect(InetAddress.getLocalHost(), port);
System.out.println("Port " + port + " is open!");
socket.disconnect();
} catch (Exception e) {
System.out.println("Port " + port + " is closed.");
}
}
socket.close();
}
}
Trace Table: Port Scanner Execution
| Port | Action | Result |
|---|---|---|
| 1024 | Connect attempt | Closed (ICMP error) |
| 1025 | Connect attempt | Open! (Service) |
| 2024 | Connect attempt | Closed |
Visual: UDP Port Scanner Flow
flowchart TD
A["Start at 1024"] --> B{"Connect?"}
B -->|"Yes"| C["Send UDP packet"]
C --> D{"Response?"}
D -->|"No"| E["Port closed"]
D -->|"Yes"| F["Port open!"]
F --> G["Next port"]7. Exam Tips
Define Key Terms Clearly
- "UDP is connectionless; multicast uses group addresses like
239.x.x.x." - "Non-blocking I/O allows threads to handle multiple sockets without waiting."
- "UDP is connectionless; multicast uses group addresses like
Code is Mandatory
- Always include sender/receiver pairs (e.g., UDP echo, multicast chat).
- Show packet construction (
DatagramPacket) and error handling (setSoTimeout).
Compare TCP vs. UDP
- Use a table (as above) to highlight reliability vs. speed.
Multicast Group Addresses
- Know the range:
224.0.0.0–239.255.255.255(reserved for multicast).
- Know the range:
Non-Blocking I/O Pitfalls
- Explain why blocking I/O is inefficient for servers (e.g., "A single thread can’t handle 10,000 clients").
Real-World Tie-Ins
- Link UDP to VoIP (e.g., WhatsApp calls) or multicast to live sports streams (e.g., YouTube TV).
Final Note: Focus on code correctness and visualizing packet flows. Examiners love seeing DatagramPacket traces and multicast group diagrams!
Based on the TU BCA syllabus for Network Programming (CACS355), unit 6.
Discussion
Loading…

