如果客户端,比如手机,发生断网、强制退出、正常退出等各种情况,服务端希望都捕捉到;
实现方法:
1. ChannelHandlerAdapter 继承ChannelHandlerAdapter,并被添加到ChannelPipeline;
ChannelPipeline pipe = ch.pipeline();
ChannelHandlerAdapter customerInboundHandler = new ChannelHandlerAdapter();
customerInboundHandler.setDriverLocationMap(driverLocationMap);
pipe.addLast(new IdleStateHandler(idleTime, idleTime, idleTime, TimeUnit.SECONDS));
pipe.addLast(new MsgDecoder(nettyDriChannelMap, nettyOriChannelMap, nettyOriMidDriMap, midPointService));
pipe.addLast(new MsgEncoder());
pipe.addLast(customerInboundHandler);
2. 在ChannelHandlerAdapter 中重写ChannelHandlerAdapter的channelInactive方法;
public class CustomerInboundHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
//channel失效处理,客户端下线或者强制退出等任何情况都触发这个方法
System.out.println("捕获异常");
super.channelInactive(ctx);
}
}
这样在channelInactive可以捕获所有异常