‘liusuyi’
2023-06-26 05e5da7edd1368a2e8f216b3efc6e87eb8d375a2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.ard.utils.tcp;
 
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;
 
/**
 * @Description:
 * @ClassName: NettyTcpClient
 * @Author: 刘苏义
 * @Date: 2023年06月25日17:00
 * @Version: 1.0
 **/
@EnableAsync
@Component
@Slf4j(topic = "radar")
public class NettyTcpClient {
    @Async
    public void init(String host, Integer port) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyTcpClientHandler());
                        }
                    });
            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 ex) {
            log.error("nettyTcp客户端初始化异常:" + ex.getMessage());
        } finally {
            group.shutdownGracefully();
        }
    }
}