Netty -09- Netty 编解码器和 handler 的调用机制

基本说明

  1. netty 的组件设计:Netty 的主要组件有 Channel、EventLoop、ChannelFuture、ChannelHandler、ChannelPipe 等
  2. ChannelHandler 充当了处理入站和出站数据的应用程序逻辑的容器。例如,实现 ChannelInboundHandler 接口(或 ChannelInboundHandlerAdapter),你就可以接收入站事件和数据,这些数据会被业务逻辑处理。当要给客户端 发送 响 应 时 , 也 可 以 从 ChannelInboundHandler 冲 刷 数 据 。 业 务 逻 辑 通 常 写 在 一 个 或 者 多 个 ChannelInboundHandler 中。ChannelOutboundHandler 原理一样,只不过它是用来处理出站数据的
  3. ChannelPipeline 提供了 ChannelHandler 链的容器。以客户端应用程序为例,如果事件的运动方向是从客户端到 服务端的,那么我们称这些事件为出站的,即客户端发送给服务端的数据会通过 pipeline 中的一系列 ChannelOutboundHandler,并被这些 Handler 处理,反之则称为入站的


编码解码器

  1. 当 Netty 发送或者接受一个消息的时候,就将会发生一次数据转换。入站消息会被解码:从字节转换为另一种 格式(比如 java 对象);如果是出站消息,它会被编码成字节
  2. Netty 提供一系列实用的编解码器,他们都实现了 ChannelInboundHadnler 或者 ChannelOutboundHandler 接口。 在这些类中,channelRead 方法已经被重写了。以入站为例,对于每个从入站 Channel 读取的消息,这个方法会 被调用。随后,它将调用由解码器所提供的 decode()方法进行解码,并将已经解码的字节转发给 ChannelPipeline 中的下一个 ChannelInboundHandler。
  3. 不论解码器handler 还是 编码器handler 即接收的消息类型必须与待处理的消息类型一致,否则该handler不会被执行
  4. 在解码器 进行数据解码时,需要判断 缓存区(ByteBuf)的数据是否足够 ,否则接收到的结果会期望结果可能不一致

解码器-ByteToMessageDecoder

  1. 关系继承图

  2. 由于不可能知道远程节点是否会一次性发送一个完整的信息,tcp 有可能出现粘包拆包的问题,这个类会对入 站数据进行缓冲,直到它准备好被处理

  3. 一个关于 ByteToMessageDecoder 实例分析

    public class ToIntegerDecoder extends ByteToMessageDecoder {
        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            if (in.readableBytes() >= 4) {
                out.add(in.readInt());
            }
        }
    }
    
    1. 这个例子,每次入站从ByteBuf中读取4字节,将其解码为一个int,然后将它添加到下一个List中。当没有更多元素可以被添加到该List中时,它的内容将会被发送给下一个ChannelInboundHandler。int在被添加到List中时,会被自动装箱为Integer。在调用readInt()方法前必须验证所输入的ByteBuf是否具有足够的数据

    2. decode 执行分析图


Netty 的 handler 链的调用机制

 使用自定义的编码器和解码器来说明 Netty 的 handler 调用机制

  • 客户端发送 long -> 服务器

  • 服务端发送 long -> 客户端


案例

server
public class Server {
    public static void main(String[] args) {
        EventLoopGroup bossGroup=new NioEventLoopGroup(1);
        EventLoopGroup workerGroup=new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap=new ServerBootstrap();

            serverBootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,128)
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ServerInitializer());

            ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(50000)).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}

serverInitializer
public class ServerInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        //入站的handler进行解码
        pipeline.addLast(new ByteToLongDecoder2());

        //加入一个出站的handler,对数据进行编码
        pipeline.addLast(new LongToByteEncoder());

        //自定义handler
        pipeline.addLast(new ServerHandler());
    }
}

serverHandler
public class ServerHandler extends SimpleChannelInboundHandler<Long> {
    /**
    * @Description 读取数据
    * @date 2020/7/24 17:56
    * @param ctx
    * @param msg
    * @return void
    */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception {
        System.out.println("从客户端"+ctx.channel().remoteAddress()+"读到的Long数据:"+msg);

        //给客户端发送一个long
        ctx.writeAndFlush(987654L);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常"+cause.getMessage()+cause.getCause()+cause.getStackTrace());
        ctx.close();
    }
}

client
public class Client {
    public static void main(String[] args) {
        EventLoopGroup group=new NioEventLoopGroup();

        try {
            Bootstrap bootstrap=new Bootstrap();

            bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ClientInitializer());

            ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress("127.0.0.1", 50000)).sync();

            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }
}

ClientInitializer
public class ClientInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();



        //加入一个出站的handler,对数据进行编码
        pipeline.addLast(new LongToByteEncoder());

        //计入一个入站的handler,对数据进行解码
        pipeline.addLast(new ByteToLongDecoder());

        //加入自定义的handler,处理业务
        pipeline.addLast(new ClientHandler());
    }
}

clientHandler
public class ClientHandler extends SimpleChannelInboundHandler<Long> {


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("发送数据...");

        //发送一个Long
        ctx.writeAndFlush(123456L);

        //        ctx.writeAndFlush(Unpooled.copiedBuffer("asdfzxcaaaaaaaaa", CharsetUtil.UTF_8));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception {
        System.out.println("收到服务器消息:"+msg);
    }


}

LongToByteEncoder
public class LongToByteEncoder extends MessageToByteEncoder<Long> {

    /**
    * @Description 编码器
    * @date 2020/7/24 18:03
    * @param ctx
    * @param msg
    * @param out
    * @return void
    */
    @Override
    protected void encode(ChannelHandlerContext ctx, Long msg, ByteBuf out) throws Exception {
        System.out.println("LongToByteEncoder 的 encode 方法被调用...");
        System.out.println("msg="+msg);
        out.writeLong(msg);
    }
}

ByteToLongDecoder
public class ByteToLongDecoder extends ByteToMessageDecoder {

    /**
    * @Description TODO
    * @date 2020/7/24 17:52
    * @param ctx  上下文对象
    * @param in  入站的ByteBuf
    * @param out  List集合,讲解码后的数据传给下一个handler
    * @return void
    */
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        System.out.println("ByteToLongDecoder 的 decode 方法被调用...");
        //每次读取8个字节
        if(in.readableBytes()>=8){
            out.add(in.readLong());
        }
    }
}

运行


传输字符

 使用上面的列子,客户端传输字符

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("发送数据...");

    //发送一个Long
    //ctx.writeAndFlush(123456L);

    //发送16个字节
    ctx.writeAndFlush(Unpooled.copiedBuffer("asdfzxcaaaaaaaaa", CharsetUtil.UTF_8));
}

 运行

 当发送的是字符串的时候,客户端不会经过编码器,服务端会将二进制解码成Long。又因为我发送的字符有16个字节,所以解码的时候回进行两次解码

  • 不论解码器 handler 还是 编码器 handler 即接收的消息类型必须与待处理的消息类型一致,否则该 handler 不 会被执行

  • 在解码器 进行数据解码时,需要判断 缓存区(ByteBuf)的数据是否足够 ,否则接收到的结果会期望结果可能 不一致


解码器-ReplayingDecoder

  1. public abstract class ReplayingDecoder extends ByteToMessageDecoder
  2. ReplayingDecoder 扩展了 ByteToMessageDecoder 类,使用这个类,我们不必调用 **readableBytes()**方法。参数S 指定了用户状态管理的类型,其中 Void 代表不需要状态管理
  3. 应用实例:使用 ReplayingDecoder 编写解码器,对前面的案例进行简化
public class ByteToLongDecoder2 extends ReplayingDecoder<Void> {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        System.out.println("ByteToLongDecoder2 的 decode 方法被调用...");
        out.add(in.readLong());
    }
}
  1. ReplayingDecoder 使用方便,但它也有一些局限性:
    • 并 不 是 所 有 的 ByteBuf 操 作 都 被 支 持 , 如 果 调 用 了 一 个 不 被 支 持 的 方 法 , 将 会 抛 出 一 个 UnsupportedOperationException
    • ReplayingDecoder 在某些情况下可能稍慢于 ByteToMessageDecoder,例如网络缓慢并且消息格式复杂时,消息会被拆成了多个碎片,速度变慢

其它编解码器

解码器
  1. LineBasedFrameDecoder:这个类在 Netty 内部也有使用,它使用行尾控制字符(\n 或者\r\n)作为分隔符来解 析数据
  2. DelimiterBasedFrameDecoder:使用自定义的特殊字符作为消息的分隔符
  3. HttpObjectDecoder:一个 HTTP 数据的解码器
  4. LengthFieldBasedFrameDecoder:通过指定长度来标识整包消息,这样就可以自动的处理黏包和半包消息


编码器

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值