如何让我的 netty 处理程序在捕获异常后继续读取数据?

How can I make my netty handler continue reading data after catching an exception?

在我的 netty 处理程序中,我覆盖了 exceptionCaught 方法以捕获由 netty ObjectDecoder 抛出的 TooLongFrameException。 如果出现该异常,我会向服务器发送一条消息,其中包含有关该错误的信息。 服务器收到该消息,然后尝试继续发送更多数据。问题是,我的处理程序似乎没有继续读取该数据。

我用的是netty 4.1.18.Final

import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.TooLongFrameException;

public final class MyHandler extends SimpleChannelInboundHandler<MyObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MyObject obj) throws Exception {

    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if (cause instanceof TooLongFrameException) {
            ctx.writeAndFlush( messageAboutError );
            return;
        } else
            ctx.writeAndFlush( messageAboutUnexpectedError );
        super.exceptionCaught(ctx, cause);
    }
}

如何让我的Handler在捕获到netty ObjectDecoder抛出的异常后继续读取数据?

真正的问题是,一旦您处于这种状态,ObjectDecoder 就会变得一团糟 "decoding state",因此除了断开连接之外,您无能为力。如果你想使用另一种消息格式,你可以做的就是丢弃消息的其余部分,只有在收到新消息后才重新开始解析。如何做到这一点等实际上取决于协议本身。