Netty的處理器重要概念
- 1纹蝴、Netty的處理器可以分為兩大類:入站處理器與出站處理器
- 2、入站處理器的頂層是ChannelInboundHandler榔幸,而出站處理器的頂層是ChannelOutboundHandler
- 3鹃唯、數(shù)據(jù)處理器時常用的各種編解碼,本質(zhì)上都是處理器
- 4弃舒、編解碼器:物流我們向網(wǎng)絡(luò)希爾的數(shù)據(jù)是什么類型(int,char,String 二進制等)數(shù)據(jù)在網(wǎng)絡(luò)傳遞時候状原,其都是以字節(jié)流的形式呈現(xiàn)的棒坏,將數(shù)據(jù)由原本的形式轉(zhuǎn)換為字節(jié)流的操作成為編碼encode,將數(shù)據(jù)由字節(jié)流轉(zhuǎn)換成原本的格式或是其他格式的操作稱為解碼(decode)遭笋,編解碼統(tǒng)稱為codec
- 5、編碼:本質(zhì)上是一種出站的處理器徒探,因此一定是ChannelOutboundHandler
- 6瓦呼、解碼:本質(zhì)上是一種入站的處理器,因此一定是ChannelInboundHandler
- 7测暗、在Netty中央串,編碼器通常以XXXEncoder命名,解碼器通常以XXXDecoder命名
*入站處理器代碼使用如:
public class MyServerHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(ctx.channel().remoteAddress() + ", " + msg);
ctx.channel().writeAndFlush("from server: " + UUID.randomUUID());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
SimpleChannelInboundHandler
ChannelInboundHandler
ChannelOutboundHandler
關(guān)于Netty編解碼的重要結(jié)論
- 1碗啄、無論是編碼器還是解碼器质和,其所接收的消息類型,必須要與待處理的參數(shù)類型一致稚字,否則該編碼器或解碼器并不會被執(zhí)行
- 2饲宿、在解碼器進行數(shù)據(jù)解碼時候厦酬,一定要記得判斷(ByteBuf)中的數(shù)據(jù)是否足夠,否則將會產(chǎn)生一些問題
組合方式管理通道句柄
- CombinedChannelDuplexHandler瘫想,從代碼里面看出來仗阅,它基礎(chǔ)ChannelDuplexHandler管道,此類有諸多重要的方法如:
bind
,channelRead
,
connect
国夜、disconnect
减噪、deregister
,而它有一個內(nèi)部類DelegatingChannelHandlerContext,它也有比較多重要的方法车吹,如:alloc
,attr
,bind
這里不寫了筹裕,請看【DelegatingChannelHandlerContext方法】截圖
CombinedChannelDuplexHandler關(guān)系圖
DelegatingChannelHandlerContext方法
DelegatingChannelHandlerContext方法