DatagramChannel UDP Messages
Send and receive UDP datagrams through DatagramChannel over loopback, showing connectionless addressing and byte buffer reuse.
Code
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.StandardCharsets;
public class DatagramChannelDemo {
public static void main(String[] args) throws Exception {
// 绑定端口 0:由系统分配空闲端口
try (DatagramChannel server = DatagramChannel.open();
DatagramChannel client = DatagramChannel.open()) {
server.bind(new InetSocketAddress("127.0.0.1", 0));
InetSocketAddress serverAddr = (InetSocketAddress) server.getLocalAddress();
System.out.println("server port: " + serverAddr.getPort());
ByteBuffer out = ByteBuffer.wrap("hello udp".getBytes(StandardCharsets.UTF_8));
client.send(out, serverAddr);
System.out.println("sent bytes: " + out.position());
ByteBuffer in = ByteBuffer.allocate(64);
InetSocketAddress from = (InetSocketAddress) server.receive(in);
in.flip();
byte[] received = new byte[in.remaining()];
in.get(received);
System.out.println("received from " + from.getPort() + ": "
+ new String(received, StandardCharsets.UTF_8));
// 向来源地址回包:数据报没有连接状态
ByteBuffer reply = ByteBuffer.wrap("ack".getBytes(StandardCharsets.UTF_8));
server.send(reply, from);
ByteBuffer in2 = ByteBuffer.allocate(64);
client.receive(in2);
in2.flip();
System.out.println("client got: " + StandardCharsets.UTF_8.decode(in2));
}
}
}How it works
DatagramChannel UDP Messages comes down to the class DatagramChannelDemo.
No finally block here — resources declared in the try header close themselves in reverse order.
Using it
The demo output is labeled (server port:, sent bytes:, received from), so every printed line maps back to its originating operation.
Key statements
ByteBuffer out = ByteBuffer.wrap("hello udp".getBytes(StandardCharsets.UTF_8));
InetSocketAddress serverAddr = (InetSocketAddress) server.getLocalAddress();
ByteBuffer reply = ByteBuffer.wrap("ack".getBytes(StandardCharsets.UTF_8));
FAQ
- What does DatagramChannel UDP Messages print when run?
- Running the file directly is enough — expect labeled output lines such as `server port:`, `sent bytes:`, `received from`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.