Netty(ChannelHandler 和 ChannelPipeline)

Netty实战(六)ChannelHandler和ChannelPipeline 可以看到上面两段代码的事件流是一样的,需要注意的是虽然被调用的 Channel 或 ChannelPipeline 上的 write()方法一直传播事件通过整个 ChannelPipeline,但是在 ChannelHandler 的级别上,事件从一个ChannelHandler到下一个 ChannelHandler 的移动是由 ChannelHandlerContext 上的调用完成的。要想处理这种类型的入站异常,你需要在你的 ChannelInboundHandler 实现中重写下面的方法。 阅读详情

ChannelHandler家族

channel的生命周期

    Interface Channel定义了一组和ChannelInboundHandler API密切相关的简单但功能强大的状态模型,其Channel主要有4个状态。

状态

描述

ChannelUnregistered

Channel 已经被创建,但还未注册到EventLoop

ChannelRegistered

Channel 已经被注册到了EventLoop

ChannelActive

Channel 处于活动状态(已经连接到它的远程节点)。它现在可以接收和发送数据了

ChannelInactive

Channel 没有连接到远程节点

    当这些状态发生改变时,将会生成对应的事件。这些事件将会被转发给ChannelPipeline中的ChannelHandler,其可以随后对它们做出响应。 

ChannelHandler的生命周期

interface ChannelHandler定义的生命周期操作如下所示,在ChannelHandler被添加到ChannelPipeline中或者被ChannelPipeline中移除时会调用 这些操作。这些方法中的每一个都接受一个ChannelHandlerContext参数。

状态

描述

handlerAdded

当把 ChannelHandler 添加到 ChannelPipeline 中时被调用

handlerRemoved

当从 ChannelPipeline 中移除 ChannelHandler 时被调用

exceptionCaught

当处理过程中在 ChannelPipeline 中有错误时被调用

 ChannelHandler有两个重要的子接口:

  • ChannelInboundHandler——处理入站数据以及各种状态变化;
  • ChannelOutboundHandler——处理出站数据并且允许拦截所有的操作。

 ChannelInboundHandler接口

以下方法将会在数据被接收时或者 与其对应的Channel状态发生改变时被调用

/**
 * {@link ChannelHandler} which adds callbacks for state changes. This allows the user
 * to hook in to state changes easily.
 */
public interface ChannelInboundHandler extends ChannelHandler {

    /**
     * 当Channel已经注册到它的EventLoop并且能够处理I/O时被调用
     */
    void channelRegistered(ChannelHandlerContext ctx) throws Exception;

    /**
     * 当Channel从它的EventLoop注销并且无法处理任何I/O时被调用
     */
    void channelUnregistered(ChannelHandlerContext ctx) throws Exception;

    /**
     * 当Channel处于活动状态时被调用;Channel已经连接/绑定并且已经就绪
     */
    void channelActive(ChannelHandlerContext ctx) throws Exception;

    /**
     * 当Channel离开活动状态并且不再连接它的远程节点时被调用
     */
    void channelInactive(ChannelHandlerContext ctx) throws Exception;

    /**
     * 当从Channel读取数据时被调用
     */
    void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception;

    /**
     * 当Channel上的一个读操作完成时被调用
     */
    void channelReadComplete(ChannelHandlerContext ctx) throws Exception;

    /**
     * 当ChannelnboundHandler.fireUserEventTriggered()方法被调用时被调用,因为一个POJO被传经了ChannelPipeline
     */
    void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception;

    /**
     * 当Channel的可写状态发生改变时被调用。用户可以确保写操作不会完成得太快(以避免发生OutOfMemoryError)或者可以在Channel变为再次可写时恢复写入。可以通过调用Channel的isWritable()方法来检测Channel的可写性。与可写性相关的阈值可以通过Channel.config().setWriteHighWaterMark()和Channel.config().setWriteLowWater-Mark()方法来设置
     */
    void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception;

    /**
     * 如果抛出一个可抛出的异常对象,则调用。
     */
    @Override
    @SuppressWarnings("deprecation")
    void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception;
}

ChannelOutboundHandler接口

    出站操作和数据将由ChannelOutboundHandler处理。它的方法将被Channel、ChannelPipeline以及ChannelHandlerContext调用。ChannelOutboundHandler的一个强大的功能是可以按需推迟操作或者事件,这使得可以通过一些复杂的方法来处理请求。例如,如果到远程节点的写入被暂停了,那么你可以推迟冲刷操作并在稍后继续。

public interface ChannelOutboundHandler extends ChannelHandler {
    /**
     * 当请求将Channel绑定到本地地址时被调用
     */
    void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception;

    /**
     * 当请求将Channel连接到远程节点时被调用
     */
    void connect(
            ChannelHandlerContext ctx, SocketAddress remoteAddress,
            SocketAddress localAddress, ChannelPromise promise) throws Exception;

    /**
     * 当请求将Channel从远程节点断开时被调用
     */
    void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception;

    /**
     * 当请求关闭Channel时被调用
     */
    void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception;

    /**
     * 当请求将Channel从它的EventLoop注销时被调用
     */
    void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception;

    /**
     * 当请求从Channel读取更多的数据时被调用
     */
    void read(ChannelHandlerContext ctx) throws Exception;

    /**
     * 当请求通过Channel将数据写到远程节点时被调用
     */
    void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception;

    /**
     * 当请求通过Channel将入队数据冲刷到远程节点时被调用
     */
    void flush(ChannelHandlerContext ctx) throws Exception;
}

    ChannelPromise与ChannelFuture ChannelOutboundHandler中的大部分方法都需要一个ChannelPromise参数,以便在操作完成时得到通知。ChannelPromise是ChannelFuture的一个子类,其定义了一些可写的方法,如setSuccess()和setFailure(),从而使ChannelFuture不可变。

ChannelHandler适配器

    ChannelInboundHandlerAdapter和ChannelOutboundHandlerAdapter类作为自己的ChannelHandler的适配器类。这两个适配器分别提供了ChannelInboundHandler和ChannelOutboundHandler的基本实现。通过扩展抽象类ChannelHandlerAdapter,它们获得了它们共同的超接口ChannelHandler的方法。生成的类的层次结构如:

    ChannelHandlerAdapter还提供了实用方法isSharable()。如果其对应的实现被标注为Sharable,那么 这个方法将返回true,表示它可以被添加到多个ChannelPipeline中。(@Sharable注解)

    在ChannelInboundHandlerAdapter和ChannelOutboundHandlerAdapter中所提供的方法体调用了其相关联的ChannelHandlerContext上的等效方法,从而将事件转发到了ChannelPipeline中的下一个ChannelHandler中。

资源管理

    为了诊断潜在的(资源泄漏)问题,Netty提供了class ResourceLeakDetector它将对你应用程序的缓冲区分配做大约1%的采样来检测内存泄露。相关的开销是非常小的。

    Netty目前定义了4种泄漏检测级别:

级别

描述

DISABLED

禁用泄漏检测。只有在详尽的测试之后才应使用

SIMPLE

使用1%的默认采样率检测并报告任何发现的泄露。这是默认级别,适合绝大部分情况。

ADVANCED

使用默认的采样率,报告所发现的任何的泄露以及对应的消息被访问的位置

PARANOID

类似于ADVANCED,但是其将会对每次(对消息的)访问都进行采样。这对性能将会有很大影响,在调试阶段使用

泄露检测级别可以通过将下面的Java系统属性设置为表中的一个值来定义:

java-Dio.netty.leakDetectionLevel=ADVANCED 

    如果一个消息被消费或者丢弃了,并且没有传递给ChannelPipeline中的下一个ChannelOutboundHandler,那么用户就有责任调用ReferenceCountUtil.release()。如果消息到达了实际的传输层,那么当它被写入时或者Channel关闭时,都将被自动释放。

ChannelPipeline接口

    ChannelPipeline是一个拦截流经Channel的入站和出站事件的Channel-Handler实例链,那么就很容易看出这些ChannelHandler之间的交互是组成一个应用程序数据和事件处理逻辑的核心。

    每一个新创建的Channel都将会被分配一个新的ChannelPipeline。这项关联是永久性的;Channel既不能附加另外一个ChannelPipeline,也不能分离其当前的。在Netty组件的生命周期中,这是一项固定的操作,不需要开发人员的任何干预。

    根据事件的起源,事件将会被ChannelInboundHandler或者ChannelOutboundHandler处理。随后,通过调用ChannelHandlerContext实现,它将被转发给同一超类型的下一个ChannelHandler。

ChannelHandlerContext:

    ChannelHandlerContext使得ChannelHandler能够和它的ChannelPipeline以及其他的ChannelHandler交互。ChannelHandler可以通知其所属的ChannelPipeline中的下一个ChannelHandler,甚至可以动态修改它所属的ChannelPipeline。         ChannelHandlerContext具有丰富的用于处理事件和执行I/O 操作的API。

    当你完成了通过调用ChannelPipeline.add*()方法将入站处理器(ChannelInboundHandler)和出站处理器(ChannelOutboundHandler)混合添加到ChannelPipeline之后,每一个ChannelHandler从头部到尾端的顺序位置正如同我们方才所定义它们的一样。因此,如果你将图中的处理器(ChannelHandler)从左到右进行编号,那么第一个被入站事件看到的ChannelHandler将是1,而第一个被出站事件看到的ChannelHandler将是 5。

    在ChannelPipeline传播事件时,它会测试ChannelPipeline中的下一个Channel-Handler的类型是否和事件的运动方向相匹配。如果不匹配,ChannelPipeline将跳过该ChannelHandler并前进到下一个,直到它找到和该事件所期望的方向相匹配的为止。

修改 ChannelPipeline

    ChannelHandler可以通过添加、删除或者替换其他的ChannelHandler来实时地修改ChannelPipeline的布局。

名称

描述

 addFirst

 addBefore

 addAfter

 addLast

将一个ChannelHandler 添加到ChannelPipeline 中

remove

将一个ChannelHandler 从 ChannelPipeline 中移除

replace

将 ChannelPipeline 中的一个 ChannelHandler 替换为另一个ChannelHandler

ChannelHandler的执行和阻塞 

    通常ChannelPipeline中的每一个ChannelHandler都是通过它的EventLoop(I/O 线程)来处理传递给它的事件的。所以至关重要的是不要阻塞这个线程,因为这会对整体的I/O 处理产生负面的影响。但有时可能需要与那些使用阻塞API  的遗留代码进行交互。对于这种情况,ChannelPipeline有一些接受一个EventExecutorGroup的add()方法。如果一个事件被传递给一个自定义的EventExecutorGroup,它将被包含在这个EventExecutorGroup中的某个EventExecutor所处理,从而被从该Channel本身的EventLoop中移除。对于这种用例,Netty提供了一个叫DefaultEventExecutor-Group的默认实现。

通过类型或者名称来访问ChannelHandler的方法:

名称

描述

 get

 通过类型或者名称返回 ChannelHandler

 context

 返回和ChannelHandler 绑定的 ChannelHandlerContext

 names

 返回ChannelPipeline 中所有 ChannelHandler 的名称

触发事件 

ChannelPipeline的API公开了用于调用入站和出站操作的附加方法:

ChannelPipeline的入站操作:

方法名称描述
fireChannelRegistered调用ChannelPipeline中下一个ChannelInboundHandler的channelRegistered(ChannelHandlerContext)方法
fireChannelUnregistered调用ChannelPipeline中下一个ChannelInboundHandler的fireChannelUnregistered(ChannelHandlerContext)方法
fireChannelActive调用ChannelPipeline中下一个ChannelInboundHandler的fireChannelActive(ChannelHandlerContext)方法
fireChannelInactive调用ChannelPipeline中下一个ChannelInboundHandler的fireChannelInactive(ChannelHandlerContext)方法
fireExceptionCaught调用ChannelPipeline中下一个ChannelInboundHandler的fireExceptionCaught(ChannelHandlerContext)方法
fireUserEventTriggered调用ChannelPipeline中下一个ChannelInboundHandler的fireUserEventTriggered(ChannelHandlerContext)方法
fireChannelRead调用ChannelPipeline中下一个ChannelInboundHandler的fireChannelRead(ChannelHandlerContext)方法
fireChannelReadComplete调用ChannelPipeline中下一个ChannelInboundHandler的fireChannelReadComplete(ChannelHandlerContext)方法
fireChannelWritabilityChanged调用ChannelPipeline中下一个ChannelInboundHandler的fireChannelWritabilityChanged(ChannelHandlerContext)方法

在出站这边,处理事件将会导致底层的套接字上发生一系列的动作。

ChannelPipeline的出站操作:

方法名称描述
bind将Channel绑定到一个本地地址,这将调用ChannelPipeline中的下一个ChannelOutboundHandler的bind(ChannelHandlerContext,Socket-Address, ChannelPromise)方法
connect将Channel连接到一个远程地址,这将调用ChannelPipeline中的下一个ChannelOutboundHandler的connect(ChannelHandlerContext, SocketAddress, ChannelPromise)方法
disconnect将Channel断开连接  。这将调用ChannelPipeline中的下一个ChannelOutboundHandler的disconnect(ChannelHandlerContext, ChannelPromise)方法
close将Channel关闭。 这将调用ChannelPipeline中的下一个ChannelOutboundHandler的close(ChannelHandlerContext, ChannelPromise)方法
deregister将Channel从它先前所分配的EventExecutor(即EventLoop)中注销。这将调用ChannelPipeline中的下一个ChannelOutboundHandler的deregister(ChannelHandlerContext, ChannelPromise)方法
flush冲刷Channel所有挂起的写入。这将调用ChannelPipeline中的下一个ChannelOutboundHandler的flush(ChannelHandlerContext)方法
write将消息写入Channel。这将调用ChannelPipeline中的下一个ChannelOutboundHandler的write(ChannelHandlerContext, Object msg, Channel-Promise)方法。注意:这并不会将消息写入底层的Socket,而只会将它放入队列中。要将它  写入Socket,需要调用flush()或者writeAndFlush()方法
writeAndFlush这是一个先调用write()方法再接着调用flush()方法的便利方法
read请求从Channel中读取更多的数据。这将调用ChannelPipeline中的下一个ChannelOutboundHandler的read(ChannelHandlerContext)方法

总结:

  • ChannelPipeline保存了与Channel相关联的ChannelHandler;
  • ChannelPipeline可以根据需要,通过添加或者删除ChannelHandler来动态地修改;
  • ChannelPipeline有着丰富的API用以被调用,以响应入站和出站事件。

ChannelHandlerContext接口 

    ChannelHandlerContext代表了ChannelHandler和ChannelPipeline之间的关联,每当有ChannelHandler添加到ChannelPipeline中时,都会创建ChannelHandlerContext。ChannelHandlerContext的主要功能是管理它所关联的ChannelHandler和在同一个ChannelPipeline中的其他ChannelHandler之间的交互。

     ChannelHandlerContext有很多的方法,其中一些方法也存在于Channel和ChannelPipeline本身上,但是有一点重要的不同。如果调用Channel或者ChannelPipeline上的这些方法,它们将沿着整个ChannelPipeline进行传播。而调用位于ChannelHandlerContext上的相同方法,则将从当前所关联的ChannelHandler开始,并且只会传播给位于该ChannelPipeline中的下一个能够处理该事件的ChannelHandler。

public interface ChannelHandlerContext extends AttributeMap, ChannelInboundInvoker, ChannelOutboundInvoker {

    /**
     * 返回绑定到这个实例的Channel
     */
    Channel channel();

    /**
     * 返回调度事件的EventExecutor
     */
    EventExecutor executor();

    /**
     * 返回这个实例的唯一名称
     */
    String name();

    /**
     * 返回绑定到这个实例的ChannelHandler
     */
    ChannelHandler handler();

    /**
     * 如果所关联的ChannelHandler已经被从ChannelPipeline中移除则返回true
     */
    boolean isRemoved();

    /**
     * 触发对下一个ChannelInboundHandler上的fireChannelRegistered()方法的调用
     */
    @Override
    ChannelHandlerContext fireChannelRegistered();

    /**
     * 触发对下一个ChannelInboundHandler上的fireChannelUnregistered()方法的调用
     */
    @Override
    ChannelHandlerContext fireChannelUnregistered();

    /**
     * 触发对下一个ChannelInboundHandler上的fireChannelActive()方法的调用
     */
    @Override
    ChannelHandlerContext fireChannelActive();

    /**
     * 触发对下一个ChannelInboundHandler上的fireChannelInactive()方法的调用
     */
    @Override
    ChannelHandlerContext fireChannelInactive();

    /**
     * 触发对下一个ChannelInboundHandler上的fireExceptionCaught()方法的调用
     */
    @Override
    ChannelHandlerContext fireExceptionCaught(Throwable cause);

    /**
     * 触发对下一个ChannelInboundHandler上的fireUserEventTriggered()方法的调用
     */
    @Override
    ChannelHandlerContext fireUserEventTriggered(Object evt);

    /**
     * 触发对下一个ChannelInboundHandler上的fireChannelRead()方法的调用
     */
    @Override
    ChannelHandlerContext fireChannelRead(Object msg);

    /**
     * 触发对下一个ChannelInboundHandler上的fireChannelReadComplete()方法的调用
     */
    @Override
    ChannelHandlerContext fireChannelReadComplete();

    /**
     * 触发对下一个ChannelInboundHandler上的fireChannelWritabilityChanged()方法的调用
     */
    @Override
    ChannelHandlerContext fireChannelWritabilityChanged();

    /**
     * 将数据从Channel读取到第一个入站缓冲区;如果读取成功则触发一个channelRead事件,并(在最后一个消息被读取完成后)通知ChannelInboundHandler的channelReadComplete(ChannelHandlerContext)方法
     */
    @Override
    ChannelHandlerContext read();

    /**
     * 刷新所有挂起的消息。
     */
    @Override
    ChannelHandlerContext flush();

    /**
     * 返回这个实例所关联的ChannelPipeline
     */
    ChannelPipeline pipeline();

    /**
     * 返回和这个实例相关联的Channel所配置的ByteBufAllocator
     */
    ByteBufAllocator alloc();

    /******************补充*************************/
    //write  通过这个实例写入消息并经过ChannelPipeline
    //writeAndFlush  通过这个实例写入并冲刷消息并经过ChannelPipeline

}

使用ChannelHandlerContext的API的时候,请牢记以下两点:

  • ChannelHandlerContext和ChannelHandler之间的关联(绑定)是永远不会改变的,所以缓存对它的引用是安全的;
  • 相对于其他类的同名方法,ChannelHandlerContext的方法将产生更短的事件流,应该尽可能地利用这个特性来获得最大的性能。

 使用 ChannelHandlerContext

修改客户端的ChildChannelHandler:

private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

        protected void initChannel(SocketChannel ch) throws Exception {
            System.out.println("客户端启动……");
            ByteBuf bufs= Unpooled.copiedBuffer("pipeline发送的数据->", Charset.forName("UTF-8"));
            ch.pipeline().write(bufs);//通过调用ChannelPipeline的write方法将数据写入通道,但是不刷新
            ch.pipeline().addLast("text",new ChannelInboundHandlerAdapter() {
                @Override
                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                    ctx.channel().write(Unpooled.copiedBuffer("通过ChannelHandlerContext获取的channel发送的消息->",
                            Charset.forName("UTF-8")));//通过ChannelHandlerContext获取的channel发送的消息->
                    CompositeByteBuf messageBuf=Unpooled.compositeBuffer();
                    ByteBuf headerBuf=buf;
                    ByteBuf bodyBuf=buf;
                    messageBuf.addComponent(bodyBuf);//将ByteBuf实例追加到CompositeByteBuf
                    messageBuf.addComponent(headerBuf);
                    for (ByteBuf buf:messageBuf){//遍历所有ByteBuf
                        System.out.println(buf);
                        byte[] req = new byte[buf.readableBytes()];
                        buf.readBytes(req);
                        String body = new String(req, "UTF-8");
                        System.out.println("复合缓冲区:"+body);
                    }
                    ctx.writeAndFlush(buf);
                }

                public void channelRead(ChannelHandlerContext ctx, Object msg)
                        throws Exception {
                    ByteBuf buf = (ByteBuf) msg;
                    ByteBuf copyBuf=((ByteBuf) msg).copy();
//                    System.out.println(buf.refCnt());//返回此对象的引用计数。如果为0,则表示此对象已被释放。
//                    buf.release();//释放引用计数对象
                    for (int i = 0; i < buf.capacity(); i++) {
                        byte b=buf.getByte(i);
                        if((char)b>='a'&&(char)b<='z'||(char)b>='A'&&(char)b<='Z'||(char)b==',')
                        System.out.println("i="+(char)b);
                    }
                    int i=buf.forEachByte(new ByteProcessor() {
                        @Override
                        public boolean process(byte value) throws Exception {
                            byte[] b=",".getBytes();
                            if (b[0]!=value)
                                return true;
                            else
                                return false;
                        }
                    });
                    System.out.println("i="+i+" value="+(char) buf.getByte(i));
                    ByteBuf sliced = buf.slice(0,2);
                    sliced.setByte(0,(byte)'h');
                    byte[] req = new byte[buf.readableBytes()];
                    buf.readBytes(req);
                    String body = new String(req, "UTF-8");
                    System.out.println(body);
                    ctx.fireChannelRead(copyBuf);
                }
            });
            ch.pipeline().addLast("text2",new ChannelInboundHandlerAdapter(){
                public void channelRead(ChannelHandlerContext ctx, Object msg)
                        throws Exception {
                    ByteBuf buf = (ByteBuf) msg;
                    byte[] req = new byte[buf.readableBytes()];
                    buf.readBytes(req);
                    String body = new String(req, "UTF-8");
                    System.out.println("text2:"+body);
                    ByteBuf bufs= Unpooled.copiedBuffer("test2发送的数据", Charset.forName("UTF-8"));
                    ctx.writeAndFlush(bufs);
                    ctx.close();
                }
            });
//            ch.pipeline().remove("text2");
        }
    }

     被调用的Channel或ChannelPipeline上的write()方法将一直传播事件通过整个ChannelPipeline,但是在ChannelHandler的级别上,事件从一个ChannelHandler到下一个ChannelHandler的移动是由ChannelHandlerContext上的调用完成的。

    要想调用从某个特定的ChannelHandler开始的处理过程,必须获取到在(ChannelPipeline)该ChannelHandler之前的ChannelHandler所关联的ChannelHandlerContext。这个ChannelHandlerContext将调用和它所关联的ChannelHandler之后的ChannelHandler。

消息将从下一个ChannelHandler开始流经ChannelPipeline,绕过了所有前面的ChannelHandler。

    因为一个ChannelHandler可以从  属于多个ChannelPipeline,所以它也可以绑定到多个ChannelHandlerContext实例。  对于这种用法   指在多个ChannelPipeline中共享同一个ChannelHandler,对应的ChannelHandler必须要使用@Sharable注解标注;否则,试图将它添加到多个ChannelPipeline时将会触发异常。显而易见,为了安全地被用于多个并发的Channel(即连接),这样的ChannelHandler必须是线程安全的。 

只应该在确定了你的ChannelHandler是线程安全的时才使用@Sharable注解。

在多个ChannelPipeline中安装同一个ChannelHandler的一个常见的原因是用于收集跨越多个Channel的统计信息。

异常处理

处理入站异常

    如果在处理入站事件的过程中有异常被抛出,那么它将从它在ChannelInboundHandler里被触发的那一点开始流经ChannelPipeline。要想处理这种类型的入站异常,你需要在你的ChannelInboundHandler实现中重写下面的方法。

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        System.out.println("服务器异常..");
        cause.printStackTrace();
        ctx.close();
    }

    因为异常将会继续按照入站方向流动(就像所有的入站事件一样),所以实现了前面所示逻辑的ChannelInboundHandler通常位于ChannelPipeline的最后。这确保了所有的入站异常都总是会被处理,无论它们可能会发生在ChannelPipeline中的什么位置。

  • ChannelHandler.exceptionCaught()的默认实现是简单地将当前异常转发给ChannelPipeline中的下一个ChannelHandler;
  • 如果异常到达了ChannelPipeline的尾端,它将会被记录为未被处理;
  • 要想定义自定义的处理逻辑,你需要重写exceptionCaught()方法。然后你需要决定是否需要将该异常传播出去。

处理出站异常 

用于处理出站操作中的正常完成以及异常的选项,都基于以下的通知机制。

  • 每个出站操作都将返回一个ChannelFuture。注册到ChannelFuture的ChannelFutureListener将在操作完成时被通知该操作是成功了还是出错了  。
  • 几乎所有的ChannelOutboundHandler上的方法都会传入一个ChannelPromise的实例。作为ChannelFuture的子类,ChannelPromise也可以被分配用于异步通知的监听器。但是,ChannelPromise还具有提供立即通知的可写方法:

   ChannelPromise setSuccess();
   ChannelPromise setFailure(Throwable cause);

添加ChannelFutureListener只需要调用ChannelFuture实例上的addListener(ChannelFutureListener)方法,并且有两种不同的方式可以做到这一点。其中最常用的方式是,调用出站操作(如write()方法)所返回的ChannelFuture上的addListener()方法。

方式一:

                    ChannelFuture future=ctx.writeAndFlush(bufs);
                    future.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            if (future.isSuccess())
                                System.out.println("成功");
                            else{
                                System.out.println("失败");
                                future.cause().printStackTrace();
                                future.channel().close();
                            }
                        }
                    });

 方式二:ChannelFutureListener添加到即将作为参数传递给ChannelOutboundHandler的方法的ChannelPromise。

public class OutboundExceptionHandler extends ChannelOutboundHandlerAdapter {
    @Override
    public void
    write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
        promise.addListener(new ChannelFutureListener() {
            @Override
            public void
            operationComplete(ChannelFuture
                                      f) {
                if (!f.isSuccess()) {
                    f.cause().printStackTrace();
                    f.channel().close();
                }
            }
        });
    }
} 

ChannelPromise的可写方法

    通过调用ChannelPromise上的setSuccess()和setFailure()方法,可以使一个操作的状态在ChannelHandler的方法返回给其调用者时便即刻被感知到。

参考《Netty实战》

附:

package netty.in.action;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.nio.charset.Charset;

public class EchoServer {

    final ByteBuf bufs= Unpooled.copiedBuffer("Hello,刘德华", Charset.forName("UTF-8"));
    public void bind(int port) throws Exception {
        //配置服务端的NIO线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 100)
                    .childHandler(new ChildChannelHandler());

            // 绑定端口,同步等待成功
            ChannelFuture f=b.bind(port).sync();

            //等待服务端监听端口关闭
            f.channel().closeFuture().sync();
        } finally {
            //退出,释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

        protected void initChannel(SocketChannel ch) throws Exception {
            System.out.println("服务端启动……");
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg)
                        throws Exception {
                    ByteBuf buf = (ByteBuf) msg;
                    if(buf.hasArray()){
                        byte[] array=buf.array();//返回该缓冲区的备份字节数组。
                        int offset=buf.arrayOffset()+buf.readerIndex();//计算第一个字节的偏移量
                        int length=buf.readableBytes();//获取可读字节数
                        String s=new String(array,offset,length);
                        System.out.println("s="+s);
                    }else{
                        byte[] array = new byte[buf.readableBytes()];//获取可读字节数并分配一个新的数组来保存
                        buf.getBytes(buf.readerIndex(),array);//将字节复制到该数组
                        String s=new String(array,0,buf.readableBytes());
                        System.out.println("直接缓冲区:"+s);
                    }
                    byte[] req = new byte[buf.readableBytes()];
                    buf.readBytes(req);
                    String body = new String(req, "UTF-8");
                    System.out.println(body);
                    bufs.retain();//引用计数器加一
                    ChannelFuture future=ctx.writeAndFlush(bufs);
                    future.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            if (future.isSuccess())
                                System.out.println("成功");
                            else{
                                System.out.println("失败");
                                future.cause().printStackTrace();
                                future.channel().close();
                            }
                        }
                    });
//                    ctx.close();
                }
            });
        }
    }

    public static void main(String[] args) throws Exception {
        int port=8080;
        new EchoServer().bind(port);
    }
}
package netty.in.action;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufProcessor;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.ByteProcessor;

import java.nio.charset.Charset;

public class EchoClient {
    final ByteBuf buf= Unpooled.copiedBuffer("Hello,王宝强", Charset.forName("UTF-8"));
    public void connect(int port, String host) throws Exception {
        // 配置客户端NIO线程组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChildChannelHandler() );
            // 发起异步连接操作
            ChannelFuture f = b.connect(host, port).sync();
            // 等待客户端链路关闭
            f.channel().closeFuture().sync();
        } finally {
            // 优雅退出,释放NIO线程组
            group.shutdownGracefully();
        }
    }

    private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

        protected void initChannel(SocketChannel ch) throws Exception {
            System.out.println("客户端启动……");
            ByteBuf bufs= Unpooled.copiedBuffer("pipeline发送的数据->", Charset.forName("UTF-8"));
            ch.pipeline().write(bufs);//通过调用ChannelPipeline的write方法将数据写入通道,但是不刷新
            ch.pipeline().addLast("text",new ChannelInboundHandlerAdapter() {
                @Override
                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                    ctx.channel().write(Unpooled.copiedBuffer("通过ChannelHandlerContext获取的channel发送的消息->",
                            Charset.forName("UTF-8")));//通过ChannelHandlerContext获取的channel发送的消息->
                    CompositeByteBuf messageBuf=Unpooled.compositeBuffer();
                    ByteBuf headerBuf=buf;
                    ByteBuf bodyBuf=buf;
                    messageBuf.addComponent(bodyBuf);//将ByteBuf实例追加到CompositeByteBuf
                    messageBuf.addComponent(headerBuf);
                    for (ByteBuf buf:messageBuf){//遍历所有ByteBuf
                        System.out.println(buf);
                        byte[] req = new byte[buf.readableBytes()];
                        buf.readBytes(req);
                        String body = new String(req, "UTF-8");
                        System.out.println("复合缓冲区:"+body);
                    }
                    ctx.writeAndFlush(buf);
                }

                public void channelRead(ChannelHandlerContext ctx, Object msg)
                        throws Exception {
                    ByteBuf buf = (ByteBuf) msg;
                    ByteBuf copyBuf=((ByteBuf) msg).copy();
//                    System.out.println(buf.refCnt());//返回此对象的引用计数。如果为0,则表示此对象已被释放。
//                    buf.release();//释放引用计数对象
                    for (int i = 0; i < buf.capacity(); i++) {
                        byte b=buf.getByte(i);
                        if((char)b>='a'&&(char)b<='z'||(char)b>='A'&&(char)b<='Z'||(char)b==',')
                        System.out.println("i="+(char)b);
                    }
                    int i=buf.forEachByte(new ByteProcessor() {
                        @Override
                        public boolean process(byte value) throws Exception {
                            byte[] b=",".getBytes();
                            if (b[0]!=value)
                                return true;
                            else
                                return false;
                        }
                    });
                    System.out.println("i="+i+" value="+(char) buf.getByte(i));
                    ByteBuf sliced = buf.slice(0,2);
                    sliced.setByte(0,(byte)'h');
                    byte[] req = new byte[buf.readableBytes()];
                    buf.readBytes(req);
                    String body = new String(req, "UTF-8");
                    System.out.println(body);
                    ctx.fireChannelRead(copyBuf);
                }
            });
            ch.pipeline().addLast("text2",new ChannelInboundHandlerAdapter(){
                public void channelRead(ChannelHandlerContext ctx, Object msg)
                        throws Exception {
                    ByteBuf buf = (ByteBuf) msg;
                    byte[] req = new byte[buf.readableBytes()];
                    buf.readBytes(req);
                    String body = new String(req, "UTF-8");
                    System.out.println("text2:"+body);
                    ByteBuf bufs= Unpooled.copiedBuffer("test2发送的数据", Charset.forName("UTF-8"));
                    ctx.writeAndFlush(bufs);
                    ctx.close();
                }
            });
//            ch.pipeline().remove("text2");
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        new EchoClient().connect(port, "127.0.0.1");
    }
}

 

Netty中ChannelPipeline和ChannelHandler的关系 ChannelPipeline为ChannelHandler链提供了容器,并定义了用于在该链上传播入站和出站事件流的API。当Channel被创建时,它会被自动地分配到它专属的ChannelPipeline。 ChannelHandler安装到ChannelPipeline中的过程: 一个ChannelInitializer的实现被注册到了ServerBootstrap(或者用于客户端的Boo... 阅读详情

相关推荐

Netty系列Netty组件之ChannelPipeline与ChannelHandler

ChannelPipeline和ChannelHandler是Netty在进行业务处理时的重要组成组件,简单来说,ChannelHandler是进行一个业务处理的处理器,而Pipeline负责将一个个的处理器串联起来,相当于一个容器,Channel中的数据会进入Pipeline,在容器中的各个处理器中按照顺序进行流转。

java1527的博客 819

Netty:ChannelInboundHandlerAdapter和ChannelOutboundHandlerAdapter

Netty:ChannelInboundHandlerAdapter和ChannelOutboundHandlerAdapter   前面说到,服务端和客户端通讯,我们通常要绑定一个handler(Netty:Bootstrap的handler和childHandler)进行通道的监听,当收到数据时就会触发某个事件,从而进行进一步的处理。 目前我们用的比较多的就是ChannelInbound...

TuxedoLinux的博客 8766

netty案例,netty4.1基础入门篇十《关于ChannelOutboundHandlerAdapter简单使用》

前言介绍 ChannelOutboundHandlerAdapter与ChannelInboundHandlerAdapter都是继承于ChannelHandler,并实现自己的ChannelXxxHandler。用于在消息管道中不同时机下处理处理消息。 ChannelInboundHandler拦截和处理入站事件,ChannelOutboundHandler拦截和处理出站事件。ChannelH...

bugstack虫洞栈 4845

异步通信框架Netty之ChannelHandlerAdapter探究

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_33725515的博客 1800

RTOS任务调度原理:高优先级任务为何在低优先级任务执行时无法响应

实时操作系统(RTOS)的核心在于其确定性的任务调度机制,它通过优先级抢占确保关键任务及时执行。其基本原理是调度器仅在特定调度点(如任务主动阻塞、中断退出时)运行,比较就绪态任务的优先级并切换上下文。这一机制的技术价值在于为嵌入式系统提供可预测的响应时间,广泛应用于工业控制、汽车电子和物联网设备等对实时性要求高的场景。当低优先级任务执行**长时间非阻塞运算**且无中断发生时,调度器无法被触发,导致高优先级任务虽处于就绪态却无法获得CPU,造成系统响应延迟。理解**任务状态机**与调度点,是优化实时性、避免此

weixin_33508411的博客 297

C# WinForm项目目录结构详解:从入门到精通(附常见问题解决方案)

本文详细解析了C# WinForm项目目录结构,从解决方案与项目基础结构到核心文件功能,再到关键目录解析,帮助开发者快速掌握WinForm项目组织方式。文章还提供了常见问题解决方案,如引用丢失、配置文件不生效等,是WinForm开发从入门到精通的实用指南。

dream的博客 656

[Netty源码] ChannelHandler相关问题 (九)

ChannelHandler相关问题

959 1159

东华大学2020考研计算机OJ题目解答分享——进阶篇(4)

4 一个月的天数 作者: Turbo时间限制: 1S章节: 分支结构 问题描述 : 输入年和月,输出该月有几天。 输入说明 : 输入两个整数,中间以空格分隔,第一个整数表示年,第二个整数表示月。 输出说明 : 输出该年该月的天数,输出时,行首与行尾均无空格,仅输出一个整数。 输入范例 : 2000 2 输出范例 : 29 解答思路: 闰年和质数出题一样频繁,简单必会 AC代码 #include...

qq_38344326的博客 480

Netty技术全解析:ChannelOutboundHandlerAdapter:简化出站事件处理的适配器

ChannelOutboundHandlerAdapter是Netty框架中处理出站事件的重要适配器类。它提供了ChannelOutboundHandler接口中所有方法的默认实现,使得用户只需要重写感兴趣的方法来处理特定的出站事件。通过使用ChannelOutboundHandlerAdapter,用户可以更加高效地开发网络应用程序,并灵活地处理各种出站事件

码到三十五 1410

pe卸载win10更新补丁_禁用Win10系统更新

众所周知,最近WIN10的强制更新导致了很多问题。如:(部分专业软件系统更新后无法使用,硬件中键盘、鼠标、指纹之类的硬件,更新补丁后失灵等问题)。而之前的禁用WindowsUpdate的方法已经失效。下面我们另辟蹊径,利用系统权限的方法使Win10无法更新,达到禁用更新的目的。1.计算机管理-服务中禁用Windows Update服务。2.打开C:\Windows\softwareDistribu...

weixin_39702479的博客 1万+

智能车竞赛飞檐走壁组赛道制作全攻略:从电磁线铺设到立体元素搭建

本文提供了智能车竞赛飞檐走壁组赛道制作的完整指南。从电磁线选材、电流控制与精准铺设等基础入手,详细解析了垂直墙面、圆筒、跷跷板等核心立体元素的构建技巧与过渡处理。重点分享了确保赛道稳定、符合规则且便于调试的实战经验,帮助参赛队伍搭建可靠的立体赛道,为车模算法调试奠定坚实基础。

weixin_29292535的博客 1324

Netty ChannelPipeline和ChannelHandler详解

Netty的ChannelPipeline采用职责链模式管理ChannelHandler,支持事件的拦截和处理。事件分为inbound(如连接建立、读事件)和outbound(如连接操作、消息发送)两类。Pipeline通过链表结构维护Handler,用户只需继承ChannelHandlerAdapter并覆盖关心的方法即可实现自定义拦截。Netty在创建Channel时会自动初始化Pipeline,开发者只需添加自定义Handler。源码分析显示Pipeline继承ChannelInboundInvoke

demon7552003的小本本 1386

先进半导体材料与器件Chapter3

Chapter3 异质结双极晶体管(HBT) 作者:毛茏玮 / Saint 掘金:https://juejin.im/user/5aa1f89b6fb9a028bb18966a 微博:https://weibo.com/5458277467/profile?topnav=1&wvr=6&is_all=1 GitHub:github.com/saint-000 知乎:https:/...

一个会写代码的烤鸭 5820

【Netty】ChannelHandler和ChannelPipeline

ChannelHandler和ChannelPipeline 在Netty组件中我们已经介绍了ChannelHandler和ChannelPipeline的关系,这里我们将继续深入了解这两个核心 组件的细节。在学习本章内容之前,请各位同学温习一遍Netty组件部分的内容。 ChannelHandler家族 Channel的生命周期 在Channel的生命周期中,它的状态与ChannelHandler是密切相关的,下列是Channel组件的四个状态: 状态 描述 ChannelUnregist

LoveSummer 3084

一文吃透 Tools for Applying SAP Notes:从 SNOTE、TCI 到 Solution Manager 与 SAP Cloud ALM

本文系统梳理了SAP技术与运维团队应用SAP Notes的高效工具与方法,涵盖On-Premise与云环境。文章首先阐述了精研SAP Notes工具的必要性,指出其是实施错误修复、法务变更和性能改进的关键载体。随后详细介绍了SNOTE、TCI、Solution Manager、Cloud ALM和Maintenance Planner等核心工具的定位与适用场景,并通过采购异常案例展示了标准更正流程。针对复杂修复场景,文章提出了TCI的批量处理方案,并强调将Note实施纳入变更治理流程的重要性。最后总结了三种

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 368

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

netty之ChannelPipeline和ChannelHandler

ChannelPipeline作为处理流水线,ChannelHandler作为流水线上的一个处理器。

多看多听多总结 1232

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Netty 的 ChannelHandler 和 ChannelPipeline

本章讲介绍: ChannelHandler 和 ChannelPipeline APIs 检测资源泄漏 异常处理 前面的章节你学习了 ByteBuf, Netty’s 的数据容器(data container). 当我们在本章中探索Netty的数据流和处理组件时,我们将以您学到的知识为基础,您将开始看到框架的重要元素汇集在一起。 您已经知道ChannelHandler可以在ChannelPip...

五石之瓠 以为大樽 浮于江湖 悠笑人生 527

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

Netty-ChannelHandler-ChannelPipeline

— | — || handlerAdded | 当把ChannelHandler添加到ChannelPipeline中时被调用 || handlerRemoved | 当从ChannelHandler在ChannelPipeline移除时调用 || exceptionCaught | 当处理过程中在ChannelPipeline中有错误产生时被调用 |Netty中定义了下面两个重要的ChannelHandler接口:ChannelInboundHandler——处理入站数据以及各种状态变化。

2501_90424598的博客 819

【Netty】ChannelPipeline和ChannelHandler(一)

欢迎关注公众号:【爱编码】 如果有需要后台回复2019赠送1T的学习资料哦!! 简介 前文学习Netty的ByteBuf数据容器。本文开始学习ChannelPipeline和ChannelHandler,它们的角色非常类似于流水线以及工人。 Channel的生命周期 Channel接口定义了一个简单但是强大的状态模型,该模型与ChannelInboundHandler API紧密联系。 Ch...

与其在害怕丢脸,不如在旅途中尽情地丢脸 1017

[netty核心类]--ChannelPipeline和ChannelHandler源码分析

本文主要包括: (1)ChannelPipeline的功能说明和源码分析; (2)ChannelHandler的功能说明和源码分析; 在netty中的ChannelPipeline和ChannelHandler的机制就很类似于J2EE中的Servlet和Filter过滤器,这类拦截器就很类似于责任链模式的一种变形。核心就是事件的拦截和用户业务逻辑的定制。netty中channel过滤器实

惜暮 2091

Netty——ChannelHandler和ChannelPipeline

ChannelHandler Channel的生命周期: Interface Channel 定义了一组和 ChannelInboundHandler API 密切相关的简单但 功能强大的状态模型,下表列出了 Channel 的这 4 个状态: 当这些状态发生改变时,将会生成对应的事件。 这些事件将会被转发给 ChannelPipeline 中的 ChannelHandler,其可以随后对它们做出响应。 ChannelHandler的生命周期: 在 ChannelHandler 被添加到 Channe

吴声子夜歌的博客 359

Netty-10 ChannelPipeline和ChannelHandler

Netty中的ChannelPipeline和ChannelHandler机制类似于Servlet和Filter过滤器,这类拦截器实际上是责任链模式的一种变种,主要是为了方便事件的拦截和用户自定义逻辑的定义。 一、ChannelPipeline (一)简单介绍 ChannelPipeline是ChannelHandler的容器,它负责ChannelHandler的管理和事件拦截与调度; (二)事件...

mail_liuxing的专栏 238

netty中的ChannelHandler和ChannelPipeline

转载自:https://www.cnblogs.com/rwxwsblog/p/7814386.html netty中的ChannelHandler和ChannelPipeline ChannelHandler 家族 https://www.w3cschool.cn/essential_netty_in_action/ Channel 生命周期 channelRegistered...

lizhengyu891231的博客 433

Netty学习——ChannelPipeLine ChannelHandler ChannelHandlerContext

先上官方图 * I/O Request * via {@link Channel} or * {@link ChannelHandlerCo...

weixin_44601714的博客 489

Netty的ChannelPipeline和ChannelHandler是什么,它们之间是如何交互的?

在 Netty 中,和是两个非常重要的组件,它们共同协作以处理网络事件和数据传输。

qq_33240556的博客 1148
上一篇: Netty(ByteBuf)
下一篇: Netty(EventLoop 和线程模型)
蛇皮皮蛋
博客等级 码龄10年 482粉丝 222原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值