Skip to content
Tutorials Center
My learning

Topics

Lesson 142 of 201 ยท Networking

UDP with DatagramSocket

Learn UDP in Java with DatagramSocket and DatagramPacket - sending and receiving packets, replies, timeouts, lost packets, retries and when UDP beats TCP.

TCP sockets give you a reliable, ordered byte stream, but that reliability has a price: a handshake before the first byte, acknowledgments for everything and waiting when a packet goes missing. UDP (User Datagram Protocol) skips all of that. You send a self-contained datagram, a packet of up to about 64 KB, to an address and port, and that's it. There's no connection, no delivery guarantee, no ordering and no retransmission.

That sounds worse, but it's exactly what some applications want. A video call would rather drop a late frame than freeze while waiting for it. A DNS lookup is a single question and a single answer, so a connection would be pure overhead. Games, live metrics, service discovery and the QUIC protocol behind HTTP/3 all build on UDP. In Java you use two classes from java.net: DatagramSocket (the endpoint) and DatagramPacket (the data plus an address). This lesson shows how to send and receive packets, reply to a sender, cope with lost packets and decide when UDP is the right tool. As before, our sandbox has no internet, so senders and receivers run in one program on 127.0.0.1.

UDP versus TCP

TCP (Socket) UDP (DatagramSocket)
Connection Handshake first, then a stream None: every packet stands alone
Delivery Guaranteed, or you get an error Best effort: packets can be lost silently
Order Always in order Can arrive out of order
Duplicates Never Possible (rare)
Message boundaries None (byte stream) Kept: one send is one receive
Overhead and latency Higher Very low
Typical uses Web, databases, file transfer, email DNS, streaming media, games, telemetry, discovery

Notice the row about message boundaries. With TCP you had to invent a protocol to find where one message ends. With UDP, every send arrives (if it arrives) as exactly one receive, with the same bytes. That makes small request/response protocols very simple.

Sending and receiving packets

A DatagramPacket plays two roles:

  • Outgoing: new DatagramPacket(bytes, length, address, port) holds the data and the destination.
  • Incoming: new DatagramPacket(buffer, buffer.length) is an empty container. socket.receive(packet) blocks until a datagram arrives, copies it into the buffer, and fills in the sender's address and port and the actual length of the data.

That last point is the most common UDP bug: the buffer is usually bigger than the message, so always build the text from packet.getData(), packet.getOffset() and packet.getLength(), never from the whole buffer.

Java A UDP sender and receiver

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

There is no accept() and no thread here. The receiver binds to a port, the sender just fires packets at it, and the operating system queues them in the receiver's buffer until receive picks them up. The sender's DatagramSocket() constructor binds to a random free port automatically, which is why packet.getPort() on the receiving side tells you where to send a reply.

On loopback, packets practically never get lost, so these demos are reliable. On real networks (Wi-Fi, mobile, the internet), loss rates of a few percent are normal, and your code must be ready for it.

Replying: a request/response server

A UDP "server" is just a socket in a loop: receive a packet, compute a reply, send it back to the packet's own address and port. Here a server on a background thread answers simple arithmetic questions, and the client sends three of them.

The server reuses one buffer for every request. That's fine because each packet's getLength() tells it how much of the buffer is valid, but there's a subtle trap: receive shrinks the packet's length to the size of the last datagram. If you reuse the same DatagramPacket object, reset its length with packet.setLength(buffer.length) before every receive, or long messages will be cut short.

Java A UDP calculator server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Calling client.connect(address) on a DatagramSocket doesn't open a connection the way TCP does. It only fixes the default destination (so packets can be built without an address) and makes the socket ignore packets from anyone else. It's a convenience, and a small security improvement for clients that talk to a single server.

Message boundaries and truncation

Because UDP keeps message boundaries, two sends never merge into one receive. The flip side: if a datagram is bigger than your receive buffer, the extra bytes are silently discarded. There is no exception and no second part; getLength() simply equals your buffer size.

Java Boundaries are kept, oversized packets are cut

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

"A" and "BB" arrive as two separate packets, as they were sent. The third message is 41 bytes, but only the first 16 fit, and the rest is gone. Size your buffers for the biggest message your protocol allows.

How big can a datagram be?

The protocol limit for IPv4 is 65,507 bytes of data. In practice, keep datagrams below about 1,200 bytes. Larger packets are split into IP fragments, and if any fragment is lost the whole datagram is lost, so big datagrams are far less reliable. That's why DNS answers, game updates and QUIC packets stay small.

Lost packets, timeouts and retries

Since UDP never retransmits, a client that sends a request and waits for a reply must handle silence itself. The standard pattern is: set a receive timeout, retry a few times, then give up. The next example simulates a lossy network: the server deliberately ignores every other request, so the client sees timeouts and retries.

Java Retrying when packets are lost

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Retries create a new problem: if the reply (not the request) was lost, the server receives the same request twice. Real protocols solve this by putting a request ID in every packet (so the client can match replies and ignore stale ones) and by making requests idempotent where possible, meaning that doing them twice is harmless. "What's the temperature?" is idempotent; "transfer 50 euros" is not, which is one reason payments don't run over plain UDP.

When you need reliability and low latency, don't build your own TCP on top of UDP. Use a protocol that already solved it, such as QUIC (through an HTTP/3 library), or just use TCP. Hand-rolled retry logic is fine for small request/response protocols like the one above.

Broadcast, multicast and channels

Two more UDP features have no TCP equivalent, because they send one packet to many receivers:

  • Broadcast: call socket.setBroadcast(true) and send to 255.255.255.255 (or a subnet's broadcast address) to reach every device on the local network. Printers and media devices use this for discovery.
  • Multicast: receivers join a group address (for example 239.1.2.3) and every packet sent to that group reaches all members. In Java you use MulticastSocket or a DatagramChannel, with the network interface to join on:
Java
var group = new InetSocketAddress(InetAddress.getByName("239.1.2.3"), 4446);
NetworkInterface nic = NetworkInterface.getByName("eth0");
try (var socket = new MulticastSocket(4446)) {
    socket.joinGroup(group, nic);
    var packet = new DatagramPacket(new byte[1500], 1500);
    socket.receive(packet);              // receives packets sent to the group
    socket.leaveGroup(group, nic);
}

Neither works on our sandbox's loopback-only network, so this code is read-only. For high-performance or non-blocking work, java.nio.channels.DatagramChannel offers the same features with ByteBuffers and can be used with a Selector.

Socket options, connected sockets and packet addresses

A DatagramSocket has a handful of settings you read with getXxx() and change with setXxx(). Each one is a thin wrapper over an operating-system socket option:

Setter / getter What it controls
setSoTimeout(ms) / getSoTimeout() How long receive blocks before throwing SocketTimeoutException; 0 means forever
setSendBufferSize(n) / getSendBufferSize() Size of the OS buffer for outgoing data; the OS may round the value, so read it back
setReceiveBufferSize(n) / getReceiveBufferSize() Size of the OS buffer for incoming datagrams. A bigger buffer loses fewer packets when your code is briefly busy
setReuseAddress(b) / getReuseAddress() Allows several sockets to bind the same port (needed for multicast listeners). Set it before binding, so create the socket with new DatagramSocket(null) and call bind afterwards
setBroadcast(b) / getBroadcast() Permission to send to broadcast addresses. It is already true by default for Java's DatagramSocket
setTrafficClass(tc) / getTrafficClass() The IP type-of-service byte: a hint to routers about priority (for example 0x10 for low delay). Routers are free to ignore it

Some getters tell you who the socket is talking to: getLocalAddress() and getLocalPort() describe your end, and getRemoteSocketAddress() returns the peer, or null while the socket is unconnected.

A UDP socket can be connected with connect(address). That does not open a connection (UDP has none), but it fixes a default peer: the socket then only accepts datagrams from that address, send no longer needs a destination in the packet, and errors such as "port unreachable" are reported to you. disconnect() undoes it. A DatagramPacket for sending needs a destination, which you set with the constructor or later with setAddress(InetAddress) plus setPort(int), or with setSocketAddress(SocketAddress), which does both in one call.

Java DatagramSocket options and packet addresses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The exact buffer sizes and traffic class that you read back depend on the operating system, which is why the example compares with >= instead of printing the numbers.

More about multicast

MulticastSocket extends DatagramSocket with the group controls. Besides joinGroup and leaveGroup:

  • setTimeToLive(int) / getTimeToLive() sets how many router hops a packet may cross. 1 (the default) keeps it on the local network; larger values let it travel further. The old setTTL/getTTL methods are deprecated; use these.
  • setInterface(InetAddress) / setNetworkInterface(NetworkInterface) choose which network card sends multicast packets on a computer with several. The matching getters are getInterface() and getNetworkInterface().
  • setLoopbackMode(boolean) controls whether your own multicast packets come back to sockets on the same machine. It is deprecated because the setting is only a hint that many systems ignore, and its logic is inverted (true disables delivery to the local machine). Do not rely on it.
Java Multicast TTL and typed channel options

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Socket options and protocol families (NIO)

The channel classes (DatagramChannel, SocketChannel, ServerSocketChannel) replace the many getters and setters with one pair of generic methods, setOption(option, value) and getOption(option). An option is a java.net.SocketOption<T> constant, and the standard ones live in StandardSocketOptions: SO_RCVBUF, SO_SNDBUF, SO_REUSEADDR, SO_BROADCAST, SO_KEEPALIVE, SO_LINGER, TCP_NODELAY, IP_TOS, IP_MULTICAST_IF, IP_MULTICAST_TTL and IP_MULTICAST_LOOP. Each constant has a name() and a type() (the Java class of its value, such as Boolean or Integer). Because the set depends on the operating system, supportedOptions() tells you which ones you may use, and setting an unsupported one throws UnsupportedOperationException.

java.net.ProtocolFamily says which kind of address a channel uses. Its standard implementation, the enum StandardProtocolFamily, has INET (IPv4), INET6 (IPv6) and, since Java 16, UNIX (local sockets between processes on one machine). You pass it to DatagramChannel.open(family) or SocketChannel.open(family). It matters for multicast: to receive IPv4 multicast groups, open the channel with INET, because an IPv6 channel on some systems cannot join an IPv4 group.

When UDP is the right choice

Choose UDP when most of these are true:

  • Messages are small and self-contained (one request, one reply, or a stream of independent updates).
  • Fresh data matters more than complete data: a late position update in a game is worthless, so retransmitting it would only add delay.
  • You need broadcast or multicast.
  • You can tolerate loss, or you can add simple retries with request IDs.

Choose TCP when you transfer files, talk to databases, send commands that must not be lost or duplicated, or simply when you're unsure. TCP is the safe default; UDP is the specialist.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A sender calls send() twice, with "hi" and then "there". The receiver calls receive() with a 1,500-byte buffer. What can it get from the first receive?

    UDP keeps message boundaries, so one send is one receive. Packets may be lost or reordered, so the first receive could even be "there". Using getLength() avoids printing the unused part of the buffer.
  2. 2. A 3,000-byte datagram arrives, but the receive buffer is 1,024 bytes. What happens?

    UDP truncates oversized datagrams without any error. getLength() equals the buffer size, which is your only hint. Size buffers for the largest message.
  3. 3. A server reuses one DatagramPacket for every receive() without calling setLength(). After a 5-byte request, a 40-byte request arrives. What does the server see?

    receive() sets the packet's length to the size of the datagram it just received. Reusing the packet without resetting setLength(buffer.length) limits the next receive to 5 bytes.
  4. 4. What does calling connect() on a DatagramSocket do?

    UDP has no connections. connect() only filters incoming packets and lets you send packets without an address. Delivery stays best effort.
  5. 5. Which of these is the best fit for UDP?

    Position updates are small, frequent and quickly outdated, so a lost one doesn't matter. The others need every byte delivered exactly once, which is TCP's job.

Summary

  • UDP sends independent datagrams with no connection, no delivery guarantee, no ordering and no retransmission, but with very low overhead and latency.
  • DatagramSocket is the endpoint; DatagramPacket carries the bytes plus a destination (outgoing) or the sender's address and the real length (incoming).
  • Read incoming data with getData(), getOffset() and getLength(), and reset setLength(buffer.length) when reusing a packet.
  • Message boundaries are kept, but oversized datagrams are silently truncated; keep packets small (about 1,200 bytes or less).
  • Reply to packet.getSocketAddress(); set setSoTimeout and retry with request IDs to handle lost packets.
  • UDP supports broadcast and multicast (MulticastSocket, DatagramChannel); prefer TCP whenever every message must arrive exactly once.

Next: The Java HTTP Client, where you'll make GET and POST requests with HttpClient against a local HTTP server.