Skip to Content
Course content

142: Building a Simple UDP Client and Server

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.