解码器Decoder和ChannelHandler的关系
netty的解码器通常是继承自ByteToMessageDecoder,而它又是继承自ChannelInboundHandlerAdapter,其实也是一种ChannelHandler和我们自定义的ChannelHandler一样都是来处理进入或者出去的数据。常用的几种解码器有:
- LineBasedFrameDecoder
- DelimiterBasedFrameDecoder
- FixedLengthFrameDecoder
LineBasedFrameDecoder
LineBasedFrameDecoder 行解码器,遍历ByteBuf中的可读字节,按行(\n \r\n)处理
StringDecoder
StringDecoder将接受的码流转换为字符串
代码中使用
1 @Override 2 protected void initChannel(SocketChannel ch) throws Exception { 3 ChannelPipeline pipeline = ch.pipeline(); 4 //LineBasedFrameDecoder遍历ByteBuf中的可读字节,按行(\n \r\n)处理 5 pipeline.addLast(new LineBasedFrameDecoder(1024)); 6 //StringDecoder将接受的码流转换为字符串 7 pipeline.addLast(new StringDecoder()); 8 pipeline.addLast(new NettyServerHandler()); 9 }
NettyServerHandler处理类中读取,String message = (String) msg;直接转换为String:
1 private int count = 0; 2 @Override 3 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 4 String message = (String) msg; 5 LOGGER.info("client received message {}:{}", ++count, message); 6 }
DelimiterBasedFrameDecoder
DelimiterBasedFrameDecoder,将特定分隔符作为码流结束标志的解码器。
代码中使用
1 @Override 2 protected void initChannel(SocketChannel ch) throws Exception { 3 ChannelPipeline pipeline = ch.pipeline(); 4 ByteBuf byteBuf = Unpooled.copiedBuffer("$_".getBytes()); 5 pipeline.addLast(new DelimiterBasedFrameDecoder(1024,true,true,byteBuf)); 6 pipeline.addLast(new StringDecoder()); 7 pipeline.addLast(new NettyServerHandler()); 8 }
FixedLengthFrameDecoder
FixedLengthFrameDecoder 固定长度解码器,只会读取指定长度的码流。
代码中使用
1 @Override 2 protected void initChannel(SocketChannel ch) throws Exception { 3 ChannelPipeline pipeline = ch.pipeline(); 4 pipeline.addLast(new FixedLengthFrameDecoder(24)); 5 pipeline.addLast(new StringDecoder()); 6 pipeline.addLast(new NettyServerHandler()); 7 }