package com.ycl.websocket.handler;
|
|
import com.ycl.websocket.NettyConnect;
|
import io.netty.channel.ChannelHandlerContext;
|
import io.netty.channel.ChannelInboundHandlerAdapter;
|
import io.netty.handler.timeout.IdleState;
|
import io.netty.handler.timeout.IdleStateEvent;
|
import io.netty.util.AttributeKey;
|
|
import java.util.Objects;
|
|
/**
|
* @author:xp
|
* @date:2024/4/19 14:41
|
*/
|
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {
|
|
private int lossConnectCount = 0;
|
@Override
|
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
|
if (evt instanceof IdleStateEvent){
|
IdleStateEvent event = (IdleStateEvent)evt;
|
if (event.state()== IdleState.READER_IDLE){
|
lossConnectCount ++;
|
if (lossConnectCount > 2){
|
AttributeKey<Long> userIdKey = AttributeKey.valueOf("userId");
|
Long userId = ctx.channel().attr(userIdKey).get();
|
if (Objects.nonNull(userId)) {
|
NettyConnect.getUserChannelMap().remove(userId);
|
}
|
NettyConnect.getChannelGroup().remove(ctx.channel());
|
ctx.channel().close();
|
}
|
}
|
}else {
|
super.userEventTriggered(ctx,evt);
|
}
|
}
|
|
}
|