diff --git "a/\347\274\226\347\250\213\350\257\255\350\250\200/JAVA/\346\241\206\346\236\266/netty.md" "b/\347\274\226\347\250\213\350\257\255\350\250\200/JAVA/\346\241\206\346\236\266/netty.md" index b1ae062eab..3635d4244c 100644 --- "a/\347\274\226\347\250\213\350\257\255\350\250\200/JAVA/\346\241\206\346\236\266/netty.md" +++ "b/\347\274\226\347\250\213\350\257\255\350\250\200/JAVA/\346\241\206\346\236\266/netty.md" @@ -133,6 +133,28 @@ public class TimeClientHandler extends ChannelInboundHandlerAdapter { 使用解码器 +```java +public class TimeDecoder extends ByteToMessageDecoder { + @Override + protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { + // 如果缓冲区没有足够的数据,不进行处理,只有缓冲区累积一定的数据时,才将数据添加到out + if (in.readableBytes() < 4){ + return; + } + // 添加到out后,代表解码器成功解码了一条消息 + out.add(in.readBytes(4)); + } +} +``` +```java +b.handler(new ChannelInitializer() { + @Override + public void initChannel(SocketChannel ch) throws Exception { + ch.pipeline().addLast(new TimeDecoder(),new TimeClientHandler()); + } +}); +``` + ## 服务端示例 - 依赖