初学netty想要写一点代码增加一些熟练度和对一些接口的认识,在前面一篇文章实现了通过事先发送长度的方法来传输自定义的message对象,这次在之前的代码上加入一些代码实现心跳检测
服务器这边首先要在管道加入idlestatehandler
之后在myhandler里加入一些代码
class myhandler extends SimpleChannelInboundHandler<message>{
/** 空闲次数 */
private int idle_count = 1;
/** 发送次数 */
private int count = 1;
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
System.err.println("one new channel in bound");
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
if (IdleState.READER_IDLE.equals(event.state())){
if (idle_count>2){
System.out.println("超过两次等待超时,关闭连接");
ctx.channel().close();
}
System.out.println("已经等待超过5秒没有用户信息");
idle_count++;
}
} else {
super.userEventTriggered(ctx, evt);
}
}
。。。。。。
这里对心跳包进行判断,如果当前连接超过2秒没有接受到数据就对idlecount进行+1如果idlecount大于2就断开连接
这样就是一个简单的心跳检测了