SocketServerHandler.java 1.92 KB
package com.ruoyi.system.handler;

import com.ruoyi.system.protocol.ThinkraceUtil;
import com.ruoyi.system.strategy.CommandStrategy;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SocketServerHandler extends ChannelInboundHandlerAdapter {
    CommandStrategy strategy;
    private static final Logger log = LoggerFactory.getLogger(SocketServerHandler.class);

    public SocketServerHandler() {
        this.strategy = new CommandStrategy();
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        // 处理指令
        strategy.handler(buf.toString(CharsetUtil.UTF_8), ctx);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//        System.out.println(ctx.channel().attr(AttributeKey.valueOf(ThinkraceUtil.IMEI)).get());
        super.channelReadComplete(ctx);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        String imei = AttributeKey.valueOf(ThinkraceUtil.IMEI).toString();
        // 发生异常触发
        ThinkraceUtil.removeDevice(imei);
        log.info("发生未知错误,设备:{}将关闭连接,原因:{}", imei, cause.getMessage());
        ctx.close();
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        ctx.channel().close();
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String imei = ctx.channel().attr(AttributeKey.valueOf(ThinkraceUtil.IMEI)).toString();
        log.info("设备断开连接了,设备号为:{}", imei);
    }
}