【问题标题】:What is the difference between channelActive and channelRead in netty?netty 中的 channelActive 和 channelRead 有什么区别?
【发布时间】:2019-09-23 16:44:54
【问题描述】:

有人知道吗 netty中channelActive和channelRead有什么区别?

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

我尝试编写一个回显服务器,以下是我的入站ChannelHandler。

我已经启动了我的 echo 服务器,当我尝试使用它的 IP 地址和端口远程登录我的服务器时,除了以下消息之外没有任何输出:“与主机的连接丢失”

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

我想知道netty中channelActive和channelRead有什么区别,为什么执行会进入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();
      }
    });
  }
}

【问题讨论】:

标签: java netty


【解决方案1】:

区别在于channelActive(...) 在通道激活后被调用(这对于 TCP 意味着通道已连接)而channelRead(...) 在收到消息后被调用。

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

【讨论】:

  • 我从一开始就知道你可能会回答我,谢谢。我想知道了,我是你在中国的粉丝
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多