Java
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Java
-
Section 4: Collections Framework
-
Section 5: Exception Handling
-
Section 6: Generics
-
Section 7: Functional Java
-
Section 8: Concurrency
-
Section 9: I/O and NIO
-
Section 10: JVM Internals
-
Section 11: Modern Java Features
-
Section 12: Build Tools and Project Structure
-
Section 13: Testing
-
Section 14: Databases and Persistence
-
Section 15: Networking
-
Section 16: Design and Best Practices
-
Section 17: Reflection and Annotations
-
Section 18: Logging and Diagnostics
-
Section 19: Date, Time, and Internationalization
-
Section 20: Java Platform Module System
-
Section 21: Security in Java
-
Section 22: Advanced Collections and Data Structures
-
Section 23: More Concurrency Patterns
-
Section 24: Compression, Files, and System Integration
-
Section 25: GUI Programming
-
Section 26: Practical Projects
-
Section 27: Data Structures and Algorithms
-
Section 28: Interview and Algorithm Practice
-
Section 29: JSON and Data Interchange
-
Section 30: More Concurrency Utilities
-
Section 31: More Collections and Streams Practice
-
Section 32: More File and System Programming
-
Section 33: Standard Library Deep Dive
-
Section 34: More Practice and Drills
-
Section 35: More Testing and Quality
-
Section 36: More Design Patterns and Architecture
-
Section 37: Career and Ecosystem
-
Section 38: More OOP and Architecture Practice
-
Section 39: More Enterprise Concepts
-
Section 40: Advanced JavaFX
-
Section 41: More Interview Practice
142: Building a Simple UDP Client and Server
Wait, if there's no "connection," how does the server actually receive data?
That's the biggest mental hurdle when moving from TCP to UDP. In TCP, you have a handshake and a dedicated stream. In UDP, you're basically throwing a postcard into the wind and hoping it hits the right mailbox. There is no ServerSocket here; both the client and the server use a DatagramSocket.
The "address" is baked into the packet itself, not the connection. When the server receives a DatagramPacket, it can call packet.getAddress() and packet.getPort() to figure out who sent the data. I usually tell people to think of it as a series of independent envelopes rather than a continuous phone call.
How do I actually send a message without using an InputStream or OutputStream?
Since UDP is packet-based, you don't "write" to a stream. Instead, you wrap your data into a DatagramPacket. You have to convert your strings to bytes because the network doesn't care about Java String objects—it only cares about raw bytes.
Let's say we're building a simple temperature sensor simulation. Here is how you'd send a reading from the client:
String sensorData = "Temp: 22.5C";
byte[] buffer = sensorData.getBytes();
InetAddress address = InetAddress.getByName("localhost");
int port = 9876;
DatagramSocket socket = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, port);
socket.send(packet);
socket.close();
Notice that I'm passing the address and port directly into the packet. That's the "mailing address" on the envelope. If you get one digit wrong, the packet just disappears into the void. No exception will be thrown because the sender has no way of knowing if the packet actually arrived.
Why do I have to provide a byte array before I even receive the data?
This is where a lot of developers get frustrated. When you call socket.receive(packet), Java doesn't dynamically resize a buffer for you. You have to provide a DatagramPacket with a pre-allocated byte array that acts as the "bucket" for the incoming data.
Here is how the server-side logic looks for our sensor example:
DatagramSocket socket = new DatagramSocket(9876);
byte[] receiveBuffer = new byte[1024]; // I usually pick a power of 2
DatagramPacket packet = new DatagramPacket(receiveBuffer, receiveBuffer.length);
System.out.println("Waiting for sensor data...");
socket.receive(packet); // This blocks until a packet arrives
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println("Received: " + received);
socket.close();
A quick word of caution: if the incoming packet is larger than your receiveBuffer, the data is simply truncated. You won't get an error; you'll just get a partial message. If you're expecting large payloads, make your buffer bigger, but keep in mind that UDP packets have a practical limit (usually around 64KB) before they get fragmented or dropped by network routers.
📋 Practical Task
Exercise: Building a UDP-Based System Monitor Alert
Your task is to create a small system that mimics a server monitoring tool. You will need to write two separate classes: a MonitorClient and a MonitorServer.
- The Client: Should generate a random integer between 1 and 100 (representing CPU usage percentage) and send it as a String to the server on port 4444.
- The Server: Should listen on port 4444. When it receives a message, it should convert the string back to an integer. If the value is 90 or higher, print "ALERT: High CPU Usage Detected!" to the console. Otherwise, print "System Healthy".
To make it realistic, try wrapping the client's send logic in a loop with a Thread.sleep(2000) so it sends an update every two seconds. Ensure your server can handle multiple packets in a loop rather than shutting down after the first one.
There are no comments for now.