关于Netty in active中第二章创建的服务端Handler不继承SimpleChannelInboundHandler的原因
2018-03-21 13:41
465 查看
书中提到这样的一段话:
为什么在服务器中不使用SimpleChannelInboundHandler呢?因为服务器要返回相同的消息给客户端,在服务器执行完成写操作之前不能释放调
用读取到的消息,因为写操作是异步的,一旦写操作完成后,Netty中会自动释放消息。而我们在重写SimpleChannelInboundHandler中的read0方法后,为什么会去回收其资源呢?我们可以在代码中看一下其实现: @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
boolean release = true;
try {
if (acceptInboundMessage(msg)) {
//判断msg是否需要在此handler中做处理,需要则调用read0,然后释放msg的资源
@SuppressWarnings("unchecked")
I imsg = (I) msg;
channelRead0(ctx, imsg);
} else {
release = false;
ctx.fireChannelRead(msg);
}
} finally {
if (autoRelease && release) {
ReferenceCountUtil.release(msg);
}
}
}
为什么在服务器中不使用SimpleChannelInboundHandler呢?因为服务器要返回相同的消息给客户端,在服务器执行完成写操作之前不能释放调
用读取到的消息,因为写操作是异步的,一旦写操作完成后,Netty中会自动释放消息。而我们在重写SimpleChannelInboundHandler中的read0方法后,为什么会去回收其资源呢?我们可以在代码中看一下其实现: @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
boolean release = true;
try {
if (acceptInboundMessage(msg)) {
//判断msg是否需要在此handler中做处理,需要则调用read0,然后释放msg的资源
@SuppressWarnings("unchecked")
I imsg = (I) msg;
channelRead0(ctx, imsg);
} else {
release = false;
ctx.fireChannelRead(msg);
}
} finally {
if (autoRelease && release) {
ReferenceCountUtil.release(msg);
}
}
}
相关文章推荐
- Netty 源码分析之SimpleChannelInboundHandler
- Netty之SimpleChannelInboundHandler
- netty之SimpleChannelInboundHandler
- 一起学Netty(三)之 SimpleChannelInboundHandler
- 一起学Netty(三)之 SimpleChannelInboundHandler
- 一起学Netty(三)之 SimpleChannelInboundHandler
- Netty中的SimpleChannelInboundHandler的通信过程
- Netty 的 inbound 与 outbound, 以及 InboundHandler 的 channelInactive 与 OutboundHandler 的 close
- netty的ChannelInboundHandler接口
- java netty之ChannelInboundByteHandlerAdapter
- netty ChannelInboundHandlerAdapter 使用注意事项
- netty ChannelInboundByteHandlerAdapter
- netty 中遇到的一个坑 SimpleInboundHandler,记录一下
- Netty 的 inbound 与 outbound, 以及 InboundHandler 的 channelInactive 与 OutboundHandler 的 close
- ChannelInboundHandlerAdapter和SimpleChannelInboundHandler的使用区分
- 关于龙哥在Netty课程中的FileChannel调用read方法返回0的原因解析
- Netty内部组件 in out bound handler等
- Netty in Action (十六) 第六章节 第二部分 ChannelHandlerContext和异常处理
- 《Netty in Action》chapter 6 : ChannelHandler and ChannelPipeline
- Netty源码:服务端Channel的创建