Skip to content

Commit f0edc8b

Browse files
committed
completed Bootstrapping client
1 parent b3f9020 commit f0edc8b

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

CORE FUNCTIONS/Bootstrapping clients and connectionless protocols.md

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ Bootstrap 类负责创建管道给客户或应用程序,利用无连接协议
2929

3030
下图展示了如何工作
3131

32-
![](../iamges/Figure 9.2 Bootstrap process.jpg)
32+
![](../images/Figure 9.2 Bootstrap process.jpg)
3333

3434
1. 当 bind() 调用时,Bootstrap 将创建一个新的管道, 当 connect() 调用在 Channel 来建立连接
3535
2. Bootstrap 将创建一个新的管道, 当 connect() 调用时
@@ -93,3 +93,48 @@ Channel 和 EventLoopGroup 的 EventLoop 必须相容,例如NioEventLoop、Nio
9393

9494
清单9.2所示的结果,试图使用一个 Channel 类型与一个 EventLoopGroup 兼容。
9595

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 的能力。
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
引导服务器
2+
====
3+

0 commit comments

Comments
 (0)