Newer
Older
casic-robot-inspection / casic-server / src / main / java / com / casic / missiles / netty / NettyClientHandler.java
casic_zt on 29 Nov 2023 2 KB 中子源重连机制优化提交
package com.casic.missiles.netty;


import com.casic.missiles.modular.neutron.service.INeutronOptService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@ChannelHandler.Sharable
@Slf4j
public class NettyClientHandler extends ChannelInboundHandlerAdapter {


    private Long userId;
    private ChannelCache channelCache;
    private INeutronOptService neutronOptService;
    private NettyClient nettyClient;


    public NettyClientHandler(Long userId, ChannelCache channelCache, INeutronOptService neutronOptService,NettyClient nettyClient) {
        this.userId = userId;
        this.channelCache = channelCache;
        this.neutronOptService = neutronOptService;
        this.nettyClient = nettyClient;
    }

    public NettyClientHandler() {
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        channelCache.addChannel(ctx.channel(), userId + "");
    }

    // 服务器端读取到 客户端发送过来的数据,然后通过 Channel 回写数据
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        log.info(String.format("客户端读取到从服务器端:%s 发送过来的数据:%s", ctx.channel().remoteAddress(), msg.toString()));
        //解析数据
        try {
            neutronOptService.analysis(ctx.channel().remoteAddress().toString(), msg.toString(), userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 捕获到异常的处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        channelCache.removeChannel(ctx.channel());
        String ipPort= ctx.channel().remoteAddress().toString();
        String[] arr=ipPort.substring(1).split(":");
        nettyClient.startClient(arr[0], Integer.valueOf(arr[1]), Long.valueOf(channelCache.getUserId(ctx.channel())));
    }


}