@@ -29,7 +29,7 @@ Bootstrap 类负责创建管道给客户或应用程序,利用无连接协议
29
29
30
30
下图展示了如何工作
31
31
32
- ![ ] (../iamges /Figure 9.2 Bootstrap process.jpg)
32
+ ![ ] (../images /Figure 9.2 Bootstrap process.jpg)
33
33
34
34
1 . 当 bind() 调用时,Bootstrap 将创建一个新的管道, 当 connect() 调用在 Channel 来建立连接
35
35
2 . Bootstrap 将创建一个新的管道, 当 connect() 调用时
@@ -93,3 +93,48 @@ Channel 和 EventLoopGroup 的 EventLoop 必须相容,例如NioEventLoop、Nio
93
93
94
94
清单9.2所示的结果,试图使用一个 Channel 类型与一个 EventLoopGroup 兼容。
95
95
96
+ Listing 9.2 Bootstrap client with incompatible EventLoopGroup
97
+
98
+ EventLoopGroup group = new NioEventLoopGroup();
99
+ Bootstrap bootstrap = new Bootstrap(); //1
100
+ bootstrap.group(group) //2
101
+ .channel(OioSocketChannel.class) //3
102
+ .handler(new SimpleChannelInboundHandler<ByteBuf>() { //4
103
+ @Override
104
+ protected void channelRead0(
105
+ ChannelHandlerContext channelHandlerContext,
106
+ ByteBuf byteBuf) throws Exception {
107
+ System.out.println("Reveived data");
108
+ byteBuf.clear();
109
+ }
110
+ });
111
+ ChannelFuture future = bootstrap.connect(
112
+ new InetSocketAddress("www.manning.com", 80)); //5
113
+ future.syncUninterruptibly();
114
+
115
+ 1 . 创建新的 Bootstrap 来创建新的客户端管道
116
+ 2 . 注册 EventLoopGroup 用于获取 EventLoop
117
+ 3 . 指定要使用的 Channel 类。通知我们使用 NIO 版本用于
118
+ EventLoopGroup , OIO 用于 Channel
119
+ 4 . 设置处理器用于管道的 I/O 事件和数据
120
+ 5 . 尝试连接到远端。当 NioEventLoopGroup 和 OioSocketChannel 不兼容时,会抛出 IllegalStateException 异常
121
+
122
+ IllegalStateException 显示如下:
123
+
124
+ Listing 9.3 IllegalStateException thrown because of invalid configuration
125
+
126
+ Exception in thread "main" java.lang.IllegalStateException: incompatible event loop
127
+ type: io.netty.channel.nio.NioEventLoop
128
+ at
129
+ io.netty.channel.AbstractChannel$AbstractUnsafe.register(AbstractChannel.java:5
130
+ 71)
131
+ ...
132
+
133
+ 出现 IllegalStateException 的其他情况是,在 bind() 或 connect() 调用前 调用需要设置参数的方法调用失败时,包括:
134
+
135
+ * group()
136
+ * channel() 或 channnelFactory()
137
+ * handler()
138
+
139
+ handler() 方法尤为重要,因为这些 ChannelPipeline 需要适当配置。
140
+ 一旦提供了这些参数,应用程序将充分利用 Netty 的能力。
0 commit comments