实现说明
DatagramChannel 收发 UDP以类 DatagramChannelDemo为骨架。
try-with-resources 保证即使方法体抛出,声明的资源也会被关闭。
使用要点
- 演示输出是带标签的(
server port:、sent bytes:、received from),每个操作都会留下自己的一行标注。
常见问题
运行「DatagramChannel 收发 UDP」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 server port:、sent bytes:、received from 标签标明各步骤。
核心语句
ByteBuffer out = ByteBuffer.wrap("hello udp".getBytes(StandardCharsets.UTF_8));
InetSocketAddress serverAddr = (InetSocketAddress) server.getLocalAddress();
ByteBuffer reply = ByteBuffer.wrap("ack".getBytes(StandardCharsets.UTF_8));
代码示例
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));
}
}
}