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; import io.netty.channel.ChannelInitializer; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; /** * @Description: 另一种tcp客户端 目前弃用 * @ClassName: NettyTcpClient * @Author: 刘苏义 * @Date: 2023年06月25日17:00 * @Version: 1.0 **/ @EnableAsync @Component @Slf4j(topic = "netty") public class NettyTcpClient { @Async("alarm") public void init(ArdEquipRadar ardEquipRadar) { while (true) { NioEventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer() { @Override protected void initChannel(SocketChannel ch) throws Exception { 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 -> { if (future1.isSuccess()) { log.info("tcp连接成功" + host + ":" + port); } else { log.info("tcp连接失败" + host + ":" + port); } }); future.channel().closeFuture().sync(); } catch (Exception e) { log.error("nettyTcp客户端初始化异常:" + e.getMessage()); try { TimeUnit.SECONDS.sleep(5); // 等待5秒后重新连接 } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } finally { group.shutdownGracefully(); } } } }