Java DatagramSocket

Su Suriya Ravichandran Updated 18 Nov 2026
12 min read ·Lesson 209 of 306

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.

FeatureTCP (Socket, ServerSocket)UDP (DatagramSocket)
ConnectionMust connect before sendingNo connection; just send
DeliveryGuaranteed, or you get an errorNot guaranteed; packets can be lost
OrderBytes arrive in orderDatagrams may arrive out of order
Message boundariesNo (a stream of bytes)Yes (one send = one datagram)
DuplicatesNeverPossible
Speed and overheadHigher overheadVery low overhead
Max message sizeUnlimited (it is a stream)65,507 bytes of data per datagram
Java data typeStreamsbyte[] 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.

MemberPurpose
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 blocked receive() throw a SocketException ("Socket closed"), which ends the server thread. This is the same shutdown technique used for ServerSocket.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 each receive(), 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 throws SocketTimeoutException with 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:

  1. 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 with getInt() on the other side.
  2. 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.
  3. Timeout means loss. The monitor uses a connected socket with setSoTimeout(300). If no reply arrives in 300 ms, the SocketTimeoutException is counted as a lost ping instead of crashing the program.
  4. 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.
  5. A small record for the result. The Result record stores the counts and calculates the loss percentage, which main() compares with a 20% threshold to decide on an alert.
  6. Clean shutdown. Closing the server socket ends the server's receive() with SocketException, and join() waits for the thread to finish.

For connection-based, reliable communication, compare this with the TCP client in Java Socket Basics.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java DatagramSocket and get answers drawn from it.

Signed-in readers only.