异常1
An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.
异常意思是为在handler进行异常处理。初步异常处理代码如下
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx,cause);
log.error("exception ", cause);
Channel channel = ctx.channel();
if (channel.isActive()) {
channel.close();
}
}
解决方法:
去掉: super.exceptionCaught(ctx,cause);
异常处理重写就不需要走默认方法了
异常2
io.netty.util.IllegalReferenceCountException refCnt: 0, decrement: 1
代码如下:
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object o) throws Exception {
if (o instanceof TextWebSocketFrame) {
TextWebSocketFrame msg = (TextWebSocketFrame) o;
//报错
ctx.writeAndFlush(msg);
//正常
ctx.writeAndFlush(msg.retain());
String text = msg.text();
//正常
ctx.writeAndFlush(new TextWebSocketFrame(text));
} else {
log.info("do some thing");
}
}
初步理解是netty的frame有内存自动释放,对象的生命周期由引用计数器控制,ByteBuf就是如此,每个对象的初始化引用计数为1,调用一次release方法,引用计数器会减1,当尝试访问计数器为0的,对象时,会抛出IllegalReferenceCountException,正如ensureAccessible的实现