Java DatagramSocket
A Java DatagramSocket sends and receives UDP packets, called datagrams. Unlike a TCP socket, it does not open a connection first: each datagram is a separate, self-contained message that carries its own destination address.
UDP is used where speed matters more than guaranteed delivery: DNS lookups, online games, live video, metrics and heartbeat checks. In this lesson you will send and receive datagrams with DatagramSocket and DatagramPacket, reply to a sender, see how message boundaries and buffers work, use receive timeouts and connected datagram sockets, and build a heartbeat monitor that measures packet loss.
UDP vs TCP in Java
The Java networking basics lesson introduced both protocols. This table shows what changes when you move from Socket to DatagramSocket.
| Feature | TCP (Socket, ServerSocket) | UDP (DatagramSocket) |
|---|---|---|
| Connection | Must connect before sending | No connection; just send |
| Delivery | Guaranteed, or you get an error | Not guaranteed; packets can be lost |
| Order | Bytes arrive in order | Datagrams may arrive out of order |
| Message boundaries | No (a stream of bytes) | Yes (one send = one datagram) |
| Duplicates | Never | Possible |
| Speed and overhead | Higher overhead | Very low overhead |
| Max message size | Unlimited (it is a stream) | 65,507 bytes of data per datagram |
| Java data type | Streams | byte[] inside a DatagramPacket |
Java DatagramSocket and DatagramPacket Classes
Two classes do all the work. DatagramSocket is the endpoint that sends and receives; DatagramPacket is the envelope that holds the bytes and the address.
| Member | Purpose |
|---|---|
new DatagramSocket() | Bind to any free local port (typical for clients) |
new DatagramSocket(port) / (port, address) | Bind to a known port (typical for servers) |
send(DatagramPacket) | Send one datagram |
receive(DatagramPacket) | Block until one datagram arrives and copy it into the packet |
setSoTimeout(ms) | Limit how long receive() waits |
connect(address) / disconnect() | Restrict the socket to one remote address |
new DatagramPacket(buf, len, address, port) | A packet to send |
new DatagramPacket(buf, len) | An empty packet to receive into |
packet.getData(), getLength() | The buffer and the number of bytes received |
packet.getAddress(), getPort(), getSocketAddress() | Who sent the datagram |
Sending and Receiving Your First Datagram
All examples use the loopback address, so the datagrams never leave your computer and the code runs offline. A receiver socket binds to port 8095, a sender socket uses any free port, and one datagram travels between them.
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
public class FirstDatagram {
public static void main(String[] args) throws Exception {
InetAddress localhost = InetAddress.getLoopbackAddress();
try (DatagramSocket receiver = new DatagramSocket(8095, localhost); // fixed port
DatagramSocket sender = new DatagramSocket()) { // any free port
// SEND: data + destination address + port
byte[] data = "Temperature: 31.5 C".getBytes(StandardCharsets.UTF_8);
DatagramPacket outgoing = new DatagramPacket(data, data.length, localhost, 8095);
sender.send(outgoing);
// RECEIVE: an empty packet with a buffer to fill
byte[] buffer = new byte[1024];
DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
receiver.receive(incoming); // blocks until a datagram arrives
String message = new String(incoming.getData(), 0, incoming.getLength(), StandardCharsets.UTF_8);
System.out.println("Message: " + message);
System.out.println("Bytes: " + incoming.getLength());
System.out.println("From host: " + incoming.getAddress().getHostAddress());
System.out.println("From sender? " + (incoming.getPort() == sender.getLocalPort()));
}
}
}
Output:
Message: Temperature: 31.5 C
Bytes: 19
From host: 127.0.0.1
From sender? true
How it works:
- The receiver binds to a fixed port (8095) so the sender knows where to send. The sender uses
new DatagramSocket(), so the OS picks a free port. - The outgoing packet holds the bytes and the destination address and port. No connection is opened.
- The incoming packet is an empty envelope around a 1024-byte buffer.
receive()blocks until a datagram arrives, then fills the buffer and sets the length and the sender's address. - Always build the text with
new String(data, 0, packet.getLength(), UTF_8). Using the whole buffer would add hundreds of empty bytes to the end of the message. incoming.getPort()equals the sender's local port, which is how a server knows where to send a reply.
Note: UDP can send a datagram to a port where nobody listens and still return without an error. Sending and receiving are fully independent.
Replying to the Sender: A UDP Echo Server
A UDP server does not get a separate socket per client, as a Java ServerSocket does. One DatagramSocket receives datagrams from everybody, and the server replies to the address stored in each received packet.
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
public class EchoReply {
public static void main(String[] args) throws Exception {
DatagramSocket server = new DatagramSocket(8095, InetAddress.getLoopbackAddress());
// Server: receive a packet, reply to whoever sent it
Thread serverThread = Thread.ofPlatform().start(() -> {
byte[] buffer = new byte[512];
try {
while (true) {
DatagramPacket request = new DatagramPacket(buffer, buffer.length);
server.receive(request);
String text = new String(request.getData(), 0, request.getLength(), StandardCharsets.UTF_8);
byte[] reply = ("ECHO " + text.toUpperCase()).getBytes(StandardCharsets.UTF_8);
// getSocketAddress() = the sender's IP and port
server.send(new DatagramPacket(reply, reply.length, request.getSocketAddress()));
}
} catch (Exception e) {
System.out.println("Server stopped: " + e.getMessage());
}
});
// Client: send three messages and read each reply
try (DatagramSocket client = new DatagramSocket()) {
for (String word : new String[] {"alpha", "beta", "gamma"}) {
byte[] data = word.getBytes(StandardCharsets.UTF_8);
client.send(new DatagramPacket(data, data.length, InetAddress.getLoopbackAddress(), 8095));
DatagramPacket reply = new DatagramPacket(new byte[512], 512);
client.receive(reply);
System.out.println(word + " -> " + new String(reply.getData(), 0, reply.getLength(), StandardCharsets.UTF_8));
}
}
server.close(); // makes receive() throw, ending the server loop
serverThread.join();
}
}
Output:
alpha -> ECHO ALPHA
beta -> ECHO BETA
gamma -> ECHO GAMMA
Server stopped: Socket closed
How it works:
- The server loop receives a datagram, converts it to text and builds a reply.
request.getSocketAddress()returns the client's IP address and port together. Passing it to the reply packet sends the answer straight back to that client.- The client sends a word and then calls
receive()to wait for the echo. server.close()makes the blockedreceive()throw aSocketException("Socket closed"), which ends the server thread. This is the same shutdown technique used forServerSocket.accept().
Message Boundaries and Buffer Size
UDP keeps message boundaries: three send() calls produce exactly three datagrams, and each receive() returns exactly one. But if the receive buffer is smaller than the datagram, the extra bytes are silently cut off.
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
public class Boundaries {
public static void main(String[] args) throws Exception {
InetAddress localhost = InetAddress.getLoopbackAddress();
try (DatagramSocket receiver = new DatagramSocket(8095, localhost);
DatagramSocket sender = new DatagramSocket()) {
// Three separate sends...
for (String part : new String[] {"first message", "second, a bit longer message", "third"}) {
byte[] data = part.getBytes(StandardCharsets.UTF_8);
sender.send(new DatagramPacket(data, data.length, localhost, 8095));
}
// ...arrive as three separate datagrams
byte[] smallBuffer = new byte[16];
DatagramPacket packet = new DatagramPacket(smallBuffer, smallBuffer.length);
for (int i = 1; i <= 3; i++) {
packet.setLength(smallBuffer.length); // reset before every receive
receiver.receive(packet);
String text = new String(packet.getData(), 0, packet.getLength(), StandardCharsets.UTF_8);
System.out.printf("Datagram %d: %2d bytes -> \"%s\"%n", i, packet.getLength(), text);
}
}
}
}
Output:
Datagram 1: 13 bytes -> "first message"
Datagram 2: 16 bytes -> "second, a bit lo"
Datagram 3: 5 bytes -> "third"
How it works:
- Each message arrives as its own datagram. With TCP, the same three writes could have been merged into one read.
- The second message is 28 bytes, but the buffer has only 16. The rest is thrown away and no exception tells you;
getLength()simply reports 16. packet.setLength(smallBuffer.length)is required when you reuse a packet. After eachreceive(), the packet's length shrinks to the size of the last datagram, and without the reset the next datagram would be cut to that size.
Note: Size the buffer for the largest message your protocol allows. On the internet, keeping datagrams under about 1,200 bytes avoids IP fragmentation, which makes loss more likely.
Receive Timeouts with setSoTimeout()
Because UDP never reports a lost packet, a client that waits for a reply could block forever. setSoTimeout() sets the longest time receive() will wait.
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
public class ReceiveTimeout {
public static void main(String[] args) throws Exception {
InetAddress localhost = InetAddress.getLoopbackAddress();
try (DatagramSocket socket = new DatagramSocket()) {
socket.setSoTimeout(700); // wait at most 700 ms in receive()
// Nobody listens on port 8096, but UDP send() still "succeeds"
byte[] data = "anyone there?".getBytes(StandardCharsets.UTF_8);
socket.send(new DatagramPacket(data, data.length, localhost, 8096));
System.out.println("send() returned without error");
DatagramPacket reply = new DatagramPacket(new byte[256], 256);
try {
socket.receive(reply);
System.out.println("Got a reply");
} catch (SocketTimeoutException e) {
System.out.println("No reply: " + e.getMessage());
}
System.out.println("Socket still usable? " + !socket.isClosed());
}
}
}
Output:
send() returned without error
No reply: Receive timed out
Socket still usable? true
How it works:
send()succeeds even though no program listens on port 8096. UDP has no handshake to fail.receive()waits 700 ms, then throwsSocketTimeoutExceptionwith the message "Receive timed out".- The socket stays open after a timeout, so the program can resend the request and wait again. Timeout-plus-retry is the usual way to make UDP requests reliable enough.
Connected DatagramSocket
Calling connect() on a DatagramSocket does not create a connection like TCP. It only remembers one remote address: the socket then sends only to that address and accepts datagrams only from it.
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
public class ConnectedDatagram {
public static void main(String[] args) throws Exception {
InetAddress localhost = InetAddress.getLoopbackAddress();
try (DatagramSocket server = new DatagramSocket(8095, localhost);
DatagramSocket client = new DatagramSocket()) {
// "Connect" the client: it may now only talk to localhost:8095
client.connect(new InetSocketAddress(localhost, 8095));
System.out.println("Connected? " + client.isConnected());
System.out.println("Remote port: " + client.getPort());
// No address needed in the packet any more
byte[] data = "status?".getBytes(StandardCharsets.UTF_8);
client.send(new DatagramPacket(data, data.length));
DatagramPacket request = new DatagramPacket(new byte[64], 64);
server.receive(request);
System.out.println("Server got: " + new String(request.getData(), 0, request.getLength(), StandardCharsets.UTF_8));
// Sending to a different address is not allowed now
try {
client.send(new DatagramPacket(data, data.length, localhost, 9999));
} catch (IllegalArgumentException e) {
System.out.println("Other target: " + e.getClass().getSimpleName());
}
client.disconnect();
System.out.println("After disconnect(): connected? " + client.isConnected());
}
}
}
Output:
Connected? true
Remote port: 8095
Server got: status?
Other target: IllegalArgumentException
After disconnect(): connected? false
How it works:
- After
connect(), the packet can be built without an address:new DatagramPacket(data, data.length)goes to the connected peer. - A packet with a different destination throws
IllegalArgumentException, which protects a client from sending to the wrong place. - A connected socket also ignores datagrams from other addresses, so strangers cannot inject fake replies.
disconnect()removes the restriction, and the socket can talk to anyone again.
Real-World Example: A UDP Heartbeat Monitor
Monitoring tools often check servers with small UDP "ping" datagrams, because they are cheap and do not tie up a connection. This example has two parts:
- A pong server that answers each ping with the same sequence number. To simulate a bad network, it ignores every third ping.
- A monitor that sends numbered pings, waits a fixed time for each reply, counts losses and raises an alert when packet loss is too high.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
public class HeartbeatMonitor {
// A UDP "pong" server that loses every third packet on purpose
static Thread startPongServer(DatagramSocket socket) {
return Thread.ofPlatform().start(() -> {
byte[] buffer = new byte[16];
try {
while (true) {
DatagramPacket ping = new DatagramPacket(buffer, buffer.length);
socket.receive(ping);
ByteBuffer in = ByteBuffer.wrap(ping.getData(), 0, ping.getLength());
int sequence = in.getInt();
if (sequence % 3 == 0) continue; // simulate network loss
byte[] pong = ByteBuffer.allocate(4).putInt(sequence).array();
socket.send(new DatagramPacket(pong, pong.length, ping.getSocketAddress()));
}
} catch (SocketException e) {
// socket closed: stop
} catch (IOException e) {
System.out.println("Server error: " + e);
}
});
}
record Result(int sent, int received) {
double lossPercent() {
return 100.0 * (sent - received) / sent;
}
}
// Send numbered pings; a reply must arrive within timeoutMs or the ping counts as lost
static Result monitor(InetSocketAddress target, int count, int timeoutMs) throws IOException {
int received = 0;
try (DatagramSocket socket = new DatagramSocket()) {
socket.connect(target);
socket.setSoTimeout(timeoutMs);
byte[] replyBuffer = new byte[16];
for (int sequence = 1; sequence <= count; sequence++) {
byte[] ping = ByteBuffer.allocate(4).putInt(sequence).array(); // 4-byte sequence number
socket.send(new DatagramPacket(ping, ping.length));
DatagramPacket reply = new DatagramPacket(replyBuffer, replyBuffer.length);
try {
socket.receive(reply);
int echoed = ByteBuffer.wrap(reply.getData(), 0, reply.getLength()).getInt();
if (echoed != sequence) {
System.out.printf("ping %d: ignored stale reply %d%n", sequence, echoed);
continue;
}
received++;
System.out.printf("ping %d: reply OK%n", sequence);
} catch (SocketTimeoutException e) {
System.out.printf("ping %d: LOST (no reply in %d ms)%n", sequence, timeoutMs);
}
}
}
return new Result(count, received);
}
public static void main(String[] args) throws Exception {
InetSocketAddress serverAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 8095);
DatagramSocket serverSocket = new DatagramSocket(serverAddress);
Thread server = startPongServer(serverSocket);
Result result = monitor(serverAddress, 7, 300);
System.out.printf("Sent %d, received %d, packet loss %.1f%%%n",
result.sent(), result.received(), result.lossPercent());
System.out.println(result.lossPercent() > 20 ? "ALERT: connection is unhealthy" : "Connection healthy");
serverSocket.close();
server.join();
}
}
Output:
ping 1: reply OK
ping 2: reply OK
ping 3: LOST (no reply in 300 ms)
ping 4: reply OK
ping 5: reply OK
ping 6: LOST (no reply in 300 ms)
ping 7: reply OK
Sent 7, received 5, packet loss 28.6%
ALERT: connection is unhealthy
How it works:
- Binary payload with ByteBuffer. Each ping carries a 4-byte sequence number written with
ByteBuffer.putInt(). Binary data keeps datagrams small and easy to parse withgetInt()on the other side. - Simulated loss. The server skips pings whose sequence number is divisible by 3, so pings 3 and 6 never get a reply, just as if the network had dropped them.
- Timeout means loss. The monitor uses a connected socket with
setSoTimeout(300). If no reply arrives in 300 ms, theSocketTimeoutExceptionis counted as a lost ping instead of crashing the program. - Sequence numbers catch stale replies. UDP can deliver late or duplicate datagrams. Comparing the echoed number with the current one ensures that a late reply to an old ping is never counted for a new one.
- A small record for the result. The
Resultrecord stores the counts and calculates the loss percentage, whichmain()compares with a 20% threshold to decide on an alert. - Clean shutdown. Closing the server socket ends the server's
receive()withSocketException, andjoin()waits for the thread to finish.
For connection-based, reliable communication, compare this with the TCP client in Java Socket Basics.