1 心跳监测
MyServer.java
public class MyServer {
public static void main(String[] args) {
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.DEBUG))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//加入Netty提供的 IdleStateHandler
/*
说明:IdleStateHandler 是netty提供的处理空闲状态的处理器
long readerIdleTime:表示多长时间没有读,就会发送一个心跳监测包 检测是否连接
long writerIdelTime:表示多长时间没有写,就会发送一个心跳监测包 监测是否连接
long allIdelTime:表示多长时间没有读写,就会发送一个心跳检测包 监测是否连接
*/
pipeline.addLast(new IdleStateHandler(3,5,7, TimeUnit.SECONDS));
//加入自定义Handler,对空闲检测进一步处理
pipeline.addLast(new MyServerHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(8000).sync();
channelFuture.channel().closeFuture().sync();
}catch (Exception e){
e.printStackTrace();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
MyServerHandler.java
@Slf4j
public class MyServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if(evt instanceof IdleStateEvent){
IdleStateEvent event = (I