HeartBeatHandler.java 3.8 KB
package com.glsx.pushsdk.biz;

import com.blankj.utilcode.util.LogUtils;
import com.glsx.pushsdk.common.CmdContants;
import com.glsx.pushsdk.common.DecoderData;
import com.glsx.pushsdk.common.Param;
import com.glsx.pushsdk.common.PushCommon;
import com.glsx.pushsdk.manager.GLPushManager;
import com.glsx.pushsdk.model.Entry;
import com.glsx.pushsdk.model.Protocol;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 心跳包
 *
 * @author YFZX-yulg 2016-11-14
 */

@ChannelHandler.Sharable
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {
    public static final String TAG = "HeartBeatReqHandler";

    private volatile ScheduledFuture<?> heartBeat;


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)            throws Exception {
        Protocol protocol = (Protocol) msg;
        if (protocol == null || protocol.getData() == null) {
            LogUtils.w(TAG,                    "channelRead, protocol is null or protocol.getData() is null");
            return;
        }

        // 验证通过后,然后发送心跳
        if (protocol.getCmdId() == CmdContants.LOGIN_BACK) {
            if (GLPushManager.getInstance().getmChannelHandlerContext() == null) {
                GLPushManager.getInstance().setmChannelHandlerContext(ctx);
            }

            if (heartBeat == null) {
                heartBeat = ctx.executor().scheduleAtFixedRate(
                        new HeartBeatTask(ctx), 0, PushCommon.HEART_REQUEST_TIME,
                        TimeUnit.SECONDS);
            }
            // 心跳响应
        } else if (CmdContants.HEART_BACK == protocol.getCmdId()) {
            Entry mEntry = DecoderData.getHearBeat(protocol.getData());
            if (mEntry.getCode() == CmdContants.SUCCESS) {
                LogUtils.w(TAG, "发送心跳成功,心跳响应 CmdId = " + protocol.getCmdId());
            }
        }
        ctx.fireChannelRead(protocol);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    private static class HeartBeatTask implements Runnable {
        private final ChannelHandlerContext ctx;

        public HeartBeatTask(final ChannelHandlerContext ctx) {
            this.ctx = ctx;
        }

        @Override
        public void run() {

            // LogUtils.w(TAG, "心跳数据发送");
            ChannelFuture future = ctx.writeAndFlush(Param.buildHeartBeatData());
            future.addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {
//						LogUtils.w(TAG, "心跳数据发送成功!");
                    } else {
//						LogUtils.w(TAG, "心跳数据发送失败!");
                    }
                }
            });
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        cancelHeartBeat();
        LogUtils.e(TAG, "exceptionCaught 业务服务器异常, ", cause);
        ctx.close();
        /* ctx.flush(); */
    }

    /**
     * 关闭心跳定时器
     */
    public synchronized void cancelHeartBeat() {
        if (heartBeat != null) {
            LogUtils.w(TAG, "关闭心跳定时器");
            heartBeat.cancel(true);
            heartBeat = null;
        }
    }

}