Class NioUdpTransport
- All Implemented Interfaces:
Transport
Transport implementation using Java NIO over UDP for lightweight, connectionless
message delivery between services or devices.
This class uses a Selector with a non-blocking DatagramChannel to receive
datagrams and a simple JSON-based envelope for outgoing messages. Each datagram is expected
to contain a single JSON object with address, payload, and type fields.
Characteristics of UDP
- Unreliable: Datagrams may be lost, duplicated, or arrive out of order.
- Message-oriented: Each packet is an independent message; there is no stream.
- No back-pressure: Sender and receiver are decoupled; overspeed can cause drops.
Message Format
{
"address": "topic.name",
"payload": ...,
"type": "send" | "publish"
}
Example usage
NioUdpTransport transport = new NioUdpTransport(9000);
transport.register("sensor.data", msg -> System.out.println("Received: " + msg));
transport.start();
// Send a message to a remote UDP listener
transport.send("localhost", 9000, "sensor.data", "Hello over UDP");
// Later:
transport.shutdown();
Note: Always call shutdown() to release resources. Consider adding your own
reliability or acknowledgement layer if message loss is unacceptable.
-
Constructor Summary
ConstructorsConstructorDescriptionNioUdpTransport(int port) Creates a new UDP transport bound to the specified local port. -
Method Summary
Modifier and TypeMethodDescriptionvoidPublishes a message intended for broadcast semantics on the receiver side.voidRegisters a handler for messages received on the specified address.voidSends a point-to-point message to the specified host and port via UDP.voidshutdown()Shuts down the transport and releases resources.voidstart()Starts the selector loop on a background thread.
-
Constructor Details
-
NioUdpTransport
Creates a new UDP transport bound to the specified local port.- Parameters:
port- the UDP port to listen on- Throws:
IOException- if the selector or channel cannot be initialized or bound
-
-
Method Details
-
start
public void start()Starts the selector loop on a background thread.When the channel is readable, a datagram is decoded as UTF-8, parsed as JSON, and dispatched to handlers based on its
addressfield and message type.Implementation note: The received buffer is reused per-iteration. Ensure
DatagramChannel.receive(java.nio.ByteBuffer)populates the buffer before decoding. -
send
Sends a point-to-point message to the specified host and port via UDP. -
publish
Publishes a message intended for broadcast semantics on the receiver side. -
shutdown
public void shutdown()Shuts down the transport and releases resources.Closes the selector and datagram channel and stops the event loop.
-
register
Registers a handler for messages received on the specified address.
-