ByteToMessageDecoder
ByteToMessageDecoder是一种ChannelInboundHandler,可以称为解码器,负责将byte字节流住(ByteBuf)转换成一种Message,Message是应用可以自己定义的一种Java对象。
例如应用中使用protobuf协议,则可以将byte转换为Protobuf对象。然后交给后面的Handler来处理。
使用示例
```
ServerBootstrap bootstrap = new ServerBootstrap();
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
bootstrap.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.DEBUG))
.group(bossGroup, workerGroup)
.childHandler(new ChannelInitializer<SocketChannel>() {
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new LineBasedFrameDecoder(1024))
.addLast(new ByteToStringDecoder())
.addLast(new StringToIntegerDecoder())
.addLast(new IntegerToByteEncoder())
.addLast(new IntegerIncHandler());
}
});
ChannelFuture bind = bootstrap.bind(8092);
bind.sync();
bind.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully().sync();
workerGroup.shutdownGracefully().sync();
}
```
这里的ChannelPipeline的组织结构是
1. ByteToStringDecoder - 将byte转换成String的Decoder
2. StringToIntegerDecoder - String转换成Integer对象的Decoder
3. IntegerToByteEncoder - Integer转换成byte的Encoder
4. IntegerIncHandler - 将接受到的int加一后返回
```
public class ByteToStringDecoder extends ByteToMessageDecoder {
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
byte[] data = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(data);
list.add(new String(data, StandardCharsets.UTF_8));
}
}
```
ByteToStringMessageDecoder继承于ByteToMessageDecoder,并实现了ByteToMessageDecoder的
`decode(ChannelHandlerContext ctx, ByteBuf in, java.util.List<java.lang.Object> out)`方法。
decode方法实现中要求将ByteBuf中的数据进行解码然后将解码后的对象增加到list中
网友评论