有人知道吗 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();
}
});
}
}
最佳答案
不同之处在于,channelActive(...)
在 channel 激活后调用(对于 TCP 而言意味着 channel 已连接)和 channelRead(...)
一旦你收到一条消息就会被调用。
当您在 channelActive(...)
中使用的 ChannelFutureListener
中直接关闭 Channel 时,您的 channelRead(...)
永远不会被调用。
关于java - netty中的channelActive和channelRead有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55998566/