netty-心跳处理器
服务器
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap()
.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))//在bossGroup增加一个日志处理器
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//加入一个netty提供的IdleStateHandler(处理空闲状态的处理器)
//参数1:多久没有读,就会发送一个心跳检测包,检测是否连接
//参数2:多久没有写,就会发送一个心跳检测包,检测是否连接
//参数3:多久既没有读也没有写,就会发送一个心跳检测包,检测是否连接
pipeline.addLast(new IdleStateHandler(3,5,7, TimeUnit.SECONDS));
//加入一个对空间检测进一步处理的自定义handler
//当IdleStateHandler的IdleStateEvent触发后,
// 就会通过pipeline传给下一个handler的userEventTiggered方法
pipeline.addLast(new MyServerHandler());
}
});
ChannelFuture cf = serverBootstrap.bind(7000).sync();
cf.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
自定义处理器
public class MyServerHandler extends ChannelInboundHandlerAdapter {
/**
*
* @param ctx 上下文
* @param evt 事件
* @throws Exception
*/
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent){
IdleStateEvent event = (IdleStateEvent) evt;
//判断空闲类型
String type = null;
switch (event.state()){
case READER_IDLE:
type = "读空闲";
break;
case WRITER_IDLE:
type = "写空闲";
break;
case ALL_IDLE:
type = "读写空闲";
}
System.out.println(ctx.channel().remoteAddress()+"发生事件:"+type);
}
}
}
注意:如果连接断开,将不会发生空闲