Skip to content

Commit 6aab4b3

Browse files
committed
completed 引导 DatagramChannel
1 parent c649006 commit 6aab4b3

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
引导 DatagramChannel
2+
====
3+
4+
在前面引导代码示例使用 SocketChannel,这是基于 tcp 的。但引导也可以用于 UDP 等无连接协议。这个使用 Netty 的提供各种DatagramChannel 实现。唯一的区别是,你无需调用 connect() 但只是 bind(),如清单9.8所示
5+
6+
Listing 9.8 Using Bootstrap with DatagramChannel
7+
8+
Bootstrap bootstrap = new Bootstrap(); //1
9+
bootstrap.group(new OioEventLoopGroup()).channel ( //2
10+
OioDatagramChannel.class) //3
11+
.handler(new SimpleChannelInboundHandler<DatagramPacket>(){ //4
12+
@Override
13+
public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
14+
// Do something with the packet
15+
}
16+
});
17+
ChannelFuture future = bootstrap.bind(new InetSocketAddress(0)); //5
18+
future.addListener(new ChannelFutureListener() {
19+
@Override
20+
public void operationComplete(ChannelFuture channelFuture) throws Exception {
21+
if (channelFuture.isSuccess()) {
22+
System.out.println("Channel bound");
23+
} else {
24+
System.err.println("Bound attempt failed");
25+
channelFuture.cause().printStackTrace();
26+
}
27+
}
28+
});
29+
30+
31+
1. 新建 Bootstrap 用于创建和绑定到新的 datagram channel
32+
2. 指定 EventLoopGroup 用来从和注册的管道中获取 EventLoop
33+
3. 指定 Channel 类
34+
4. 设置处理器来处理管道中的 I/O 和数据
35+
5. 当协议是无连接时,调用 bind()

0 commit comments

Comments
 (0)