package com.nokia.service.handler;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class HeartbeatHandler extends ChannelDuplexHandler {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            // 如果60秒没有写操作，就发送心跳消息
            if (((IdleStateEvent) evt).state().equals(IdleState.WRITER_IDLE)) {
                // 发送心跳消息
                ctx.writeAndFlush("<HeartBeat>\r\nProvinceID:18\r\n</HeartBeat>\r\n");
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
