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

标签 java netty

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

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

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

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

当我调试我的代码时,我发现执行进入方法 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(...) 在 channel 激活后调用(对于 TCP 而言意味着 channel 已连接)和 channelRead(...) 一旦你收到一条消息就会被调用。

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

关于java - netty中的channelActive和channelRead有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55998566/

相关文章:

java - Python 的 urllib2.urlopen() 挂起与 Java ReSTLet 服务器的本地连接

java - 创建通用重映射函数

Java计算排序数组中每个项目的出现次数

java - 连接由对等方使用异步 http 客户端和 netty 重置

java - 如何从 Linux shell 运行一个简单的类文件?

本地计算机上的 Java Applet 获得 AccessControlExceptions,这取决于代码路径

java - 我可以在非Netty线程中调用 `Channel.write()`吗?

java - 用 netty 发送后我无法转换我的对象

java - 使用非阻塞架构管理 DTLS

performance - 与 Netty 相比,vert.x 如何实现卓越的性能?