java – 在Netty中通道处理程序的ChannelInitializer的优势
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 在Netty中通道处理程序的ChannelInitializer的优势,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1852字,纯文字阅读大概需要3分钟。
内容图文
直接在ChannelHandler链上使用ChannelInitializer有什么好处?
例如,使用服务器引导程序,我可以这样做:
bootstrap.childHandler(channel_handler);
添加channel_handler的实现我将实现以下内容
class simple_channel_handler implements ChannelHandler
{
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
System.out.println("handler added");
ctx.pipeline().addLast(new simple_channel_handler_2());
}
}
在ChannelInitializer的情况下
ch.pipeline().addLast(
new channel_handler_1(),
new channel_handler_2()
);
在我可以做的每一个处理程序中
class channel_handler_1 extends ChannelInboundHandlerAdapter
{
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
System.out.println("Channel just became active");
ctx.fireChannelRead(ctx); // Fire directly to channel handler 2
}
}
因此,通道处理程序无需了解触发通道读取的唯一优势是什么?我没有看到使用频道初始化器的任何其他优势
解决方法:
根据文档(见这里http://netty.io/wiki/user-guide-for-4.x.html)
The handler specified here will always be evaluated by a newly
accepted Channel. The ChannelInitializer is a special handler that is
purposed to help a user configure a new Channel. It is most likely
that you want to configure the ChannelPipeline of the new Channel by
adding some handlers such as DiscardServerHandler to implement your
network application. As the application gets complicated, it is likely
that you will add more handlers to the pipeline and extract this
anonymous class into a top level class eventually.
所以ChannelInitializer是一种干净的方式来根据需要添加处理程序,特别是如果你有多个.
它不会阻止一个处理程序添加更多处理程序(正如您在第一个示例中所做的那样),例如根据上下文动态添加/删除管道中的一个处理程序,但是对于“静态”或“默认”系列处理程序使用ChannelInitializer是一种更干净的方式,因为它非常接近引导程序定义,因此更具可读性.
内容总结
以上是互联网集市为您收集整理的java – 在Netty中通道处理程序的ChannelInitializer的优势全部内容,希望文章能够帮你解决java – 在Netty中通道处理程序的ChannelInitializer的优势所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。