解碼器Decoder和ChannelHandler的關系
netty的解碼器通常是繼承自ByteToMessageDecoder,而它又是繼承自ChannelInboundHandlerAdapter,其實也是一種ChannelHandler和我們自定義的ChannelHandler一樣都是來處理進入或者出去的數據。常用的幾種解碼器有:
- LineBasedFrameDecoder
- DelimiterBasedFrameDecoder
- FixedLengthFrameDecoder
LineBasedFrameDecoder
LineBasedFrameDecoder 行解碼器,遍歷ByteBuf中的可讀字節,按行(\n \r\n)處理
StringDecoder
StringDecoder將接受的碼流轉換為字符串
代碼中使用
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//LineBasedFrameDecoder遍歷ByteBuf中的可讀字節,按行(\n \r\n)處理
pipeline.addLast(new LineBasedFrameDecoder(1024));
//StringDecoder將接受的碼流轉換為字符串
pipeline.addLast(new StringDecoder());
pipeline.addLast(new NettyServerHandler());
}
NettyServerHandler處理類中讀取,String message = (String) msg;直接轉換為String:
private int count = 0;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String message = (String) msg;
LOGGER.info("client received message {}:{}", ++count, message);
}
DelimiterBasedFrameDecoder
DelimiterBasedFrameDecoder,將特定分隔符作為碼流結束標志的解碼器。
代碼中使用
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
ByteBuf byteBuf = Unpooled.copiedBuffer("$_".getBytes());
pipeline.addLast(new DelimiterBasedFrameDecoder(1024,true,true,byteBuf));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new NettyServerHandler());
}
FixedLengthFrameDecoder
FixedLengthFrameDecoder 固定長度解碼器,只會讀取指定長度的碼流。
代碼中使用
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new FixedLengthFrameDecoder(24));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new NettyServerHandler());
}