package com.pwt.netty.client.dispatcher;

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

/**
 * 扫码器连接保活handler
 *
 * @author zk
 */
public class KeepaliveHandler extends ChannelDuplexHandler {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent) {
            // 触发第一次空闲时，向发一条空消息
            if(((IdleStateEvent)evt).state() == IdleState.READER_IDLE) {
                ByteBuf buffer = ctx.alloc().buffer();
                buffer.writeByte(0);
                // 注: 写入后不需要手动释放buffer, netty的write方法中会调用buffer释放
                ctx.channel().writeAndFlush(buffer);
            }
        }
        super.userEventTriggered(ctx, evt);
    }
}
