netty中的channelActive和channelRead有什么区别?

What is the difference between channelActive and channelRead in netty?

有谁知道 netty中的channelActive和channelRead有什么区别?

我正在通过阅读 Netty 用户指南来学习 Netty (https://netty.io/wiki/user-guide-for-4.x.html)

我试过写一个回显服务器,下面是我的入站ChannelHandler

我已经启动了我的 echo 服务器,当我尝试使用它的 IP 地址和端口远程登录我的服务器时,除了消息之外没有任何输出:"Lost connection to host machine"

当我调试我的代码时,我发现执行进入了方法 channelActive 但没有进入 channelRead.

想知道netty中channelActivechannelRead有什么区别,为什么执行会进入channelActive

以下是我的ChannelHandler

package com.yjz.middleware.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.ReferenceCounted;

import java.nio.Buffer;

public class DiscardServerHandler extends ChannelInboundHandlerAdapter {
  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;
    System.out.print(in.toString(CharsetUtil.UTF_8));
    ctx.write(msg);
    ctx.flush();
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    // Close the connection when an exception is raised.
    cause.printStackTrace();
    ctx.close();
  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    final ByteBuf time = ctx.alloc().buffer(4);
    time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L));
    final ChannelFuture f = ctx.writeAndFlush(time);
    f.addListener(new ChannelFutureListener() {
      @Override
      public void operationComplete(ChannelFuture future) throws Exception {
        assert f == future;
        ctx.close();
      }
    });
  }
}

不同之处在于,channelActive(...) 在通道激活后调用(对于 TCP 而言意味着通道已连接),而 channelRead(...) 在收到消息后调用。

当您在 channelActive(...) 中使用的 ChannelFutureListener 中直接关闭频道时,您的 channelRead(...) 永远不会被调用。