/*** Created by fubin on 2019/7/13.*/
public classBeartBeatServer {public static voidmain(String[] args) {
EventLoopGroup bossGroup= newNioEventLoopGroup();
EventLoopGroup workerGroup= newNioEventLoopGroup();try{
ServerBootstrap serverBootstrap= newServerBootstrap();
serverBootstrap.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)//增加日志handler
.handler(newLoggingHandler(LogLevel.INFO))
.childHandler(newHeartBeatInitializer());
ChannelFuture channelFuture= serverBootstrap.bind(8899).sync();
channelFuture.channel().closeFuture().sync();
}catch(InterruptedException e) {
e.printStackTrace();
}finally{
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}class HeartBeatInitializer extends ChannelInitializer{protected void initChannel(SocketChannel socketChannel) throwsException {
ChannelPipeline channelPipeline=socketChannel.pipeline();//netty还提供了各种各样的处理器,比如空闲检测的handler
channelPipeline.addLast(new IdleStateHandler(5,7,10, TimeUnit.SECONDS));
channelPipeline.addLast(newHeartBeatHandler());
}
}class HeartBeatHandler extendsChannelInboundHandlerAdapter {
@Overridepublic void userEventTriggered(ChannelHandlerContext ctx, Object evt) throwsException {
IdleStateEvent event=(IdleStateEvent)evt;
String eventType= null;switch(event.state()){caseREADER_IDLE:
eventType= "读空闲";break;caseWRITER_IDLE:
eventType= "写空闲";break;caseALL_IDLE:
eventType= "读写空闲";break;
}
System.out.println(ctx.channel().remoteAddress()+ "超时事件:" +eventType);
ctx.channel().close();
}
}