‘liusuyi’
2023-06-27 3be4440f6800e10efd8db51b957d17a6cc3b39df
src/main/java/com/ard/utils/tcp/NettyTcpClient.java
@@ -1,5 +1,6 @@
package com.ard.utils.tcp;
import com.ard.alarm.radar.domain.ArdEquipRadar;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
@@ -11,6 +12,8 @@
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
 * @Description:
@@ -24,7 +27,9 @@
@Slf4j(topic = "radar")
public class NettyTcpClient {
    @Async
    public void init(String host, Integer port) {
    public void init(ArdEquipRadar ardEquipRadar) {
        while (true) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
@@ -33,9 +38,11 @@
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyTcpClientHandler());
                                ch.pipeline().addLast(new NettyTcpClientHandler(ardEquipRadar));
                        }
                    });
                String host = ardEquipRadar.getIp();
                Integer port = ardEquipRadar.getPort();
            ChannelFuture future = bootstrap.connect(host, port).sync();
            // 添加连接成功的监听器
            future.addListener((ChannelFutureListener) future1 -> {
@@ -47,10 +54,16 @@
            });
            future.channel().closeFuture().sync();
        } catch (Exception ex) {
            log.error("nettyTcp客户端初始化异常:" + ex.getMessage());
            } catch (Exception e) {
                log.error("nettyTcp客户端初始化异常:" + e.getMessage());
                try {
                    TimeUnit.SECONDS.sleep(5); // 等待5秒后重新连接
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
        } finally {
            group.shutdownGracefully();
        }
    }
}
}