NettyReceiverHandler.java 2.31 KB
package com.viontech.netty;


import com.viontech.configuration.PropertiesConfiguration;
import com.viontech.model.BaseModel;
import com.viontech.model.KeepAlive;
import com.viontech.model.LoginData;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;


/**
 * @author 谢明辉
 */
@Slf4j
public class NettyReceiverHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        log.info("channelRegistered----------------");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof BaseModel) {
            BaseModel message = (BaseModel) msg;

            //注册命令
            if (message instanceof LoginData) {
                BaseModel result = new BaseModel().setDeviceId(0L).setLength(16L).setProtocol(0x00020100L);

                LoginData logindata = (LoginData) message;
                Long deviceId = logindata.getDeviceId();

                if (PropertiesConfiguration.username.equals(logindata.getUsername()) &&
                        PropertiesConfiguration.password.equals(logindata.getPassword())) {
                    log.info("注册成功");
                    ChannelGroup.registered(deviceId, ctx.channel());
                    result.setFlag(0L);
                } else {
                    log.info("注册失败,用户名:[{}],密码:[{}]", logindata.getUsername(), logindata.getPassword());
                    result.setFlag(1L);
                }
                ctx.writeAndFlush(result).await();
            } else if (message instanceof KeepAlive) {
                log.info("收到心跳,设备ID:[{}]", message.getDeviceId());
            }
            ReferenceCountUtil.release(msg);
            ctx.fireChannelReadComplete();
        }
    }

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

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) {
        log.info("断开连接:{}", ctx.channel().id().toString());
    }
}