IdleStateHandler
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup)
.channel(ServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
// readerIdleTime 读空闲时间
// writerIdleTime 写空闲时间
// allIdleTime 读写都空闲时间
// 发生后会调用之后的handler中的userEventTriggered方法,有三种事件枚举
pipeline.addLast(new IdleStateHandler(3, 5, 8, TimeUnit.SECONDS));
// 加入一个对空闲检测进一步处理的handler
pipeline.addLast(new MyServerHandler);
}
});
复制代码
事件枚举
public enum IdleState {
READER_IDLE, // 读空闲
WRITER_IDLE, // 写空闲
ALL_IDLE; // 读写空闲
private IdleState() {
}
}
复制代码
事件handler
public class MyServerHandler extends ChannelInboundHandlerAdapter {
/**
* 用户事件触发
*
* @param ctx ctx
* @param evt evt
* @throws Exception 异常
*/
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
switch (event.state()) {
case READER_IDLE:
case ALL_IDLE:
case WRITER_IDLE:
default:
break;
}
}
}
}
复制代码
近期评论