W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
在所有的例子代碼中,我們?cè)谝龑?dǎo)過程中通過 handler() 或childHandler() 都只添加了一個(gè) ChannelHandler 實(shí)例,對(duì)于簡(jiǎn)單的程序可能足夠,但是對(duì)于復(fù)雜的程序則無法滿足需求。例如,某個(gè)程序必須支持多個(gè)協(xié)議,如 HTTP、WebSocket。若在一個(gè) ChannelHandle r中處理這些協(xié)議將導(dǎo)致一個(gè)龐大而復(fù)雜的 ChannelHandler。Netty 通過添加多個(gè) ChannelHandler,從而使每個(gè) ChannelHandler 分工明確,結(jié)構(gòu)清晰。
Netty 的一個(gè)優(yōu)勢(shì)是可以在 ChannelPipeline 中堆疊很多ChannelHandler 并且可以最大程度的重用代碼。如何添加多個(gè)ChannelHandler 呢?Netty 提供 ChannelInitializer 抽象類用來初始化 ChannelPipeline 中的 ChannelHandler。ChannelInitializer是一個(gè)特殊的 ChannelHandler,通道被注冊(cè)到 EventLoop 后就會(huì)調(diào)用ChannelInitializer,并允許將 ChannelHandler 添加到CHannelPipeline;完成初始化通道后,這個(gè)特殊的 ChannelHandler 初始化器會(huì)從 ChannelPipeline 中自動(dòng)刪除。
聽起來很復(fù)雜,其實(shí)很簡(jiǎn)單,看下面代碼:
Listing 9.6 Bootstrap and using ChannelInitializer
ServerBootstrap bootstrap = new ServerBootstrap();//1
bootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup()) //2
.channel(NioServerSocketChannel.class) //3
.childHandler(new ChannelInitializerImpl()); //4
ChannelFuture future = bootstrap.bind(new InetSocketAddress(8080)); //5
future.sync();
final class ChannelInitializerImpl extends ChannelInitializer<Channel> { //6
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline(); //7
pipeline.addLast(new HttpClientCodec());
pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
}
}
通過 ChannelInitializer, Netty 允許你添加你程序所需的多個(gè) ChannelHandler 到 ChannelPipeline
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: