| File was renamed from ard-work/src/main/java/com/ard/tianyu/component/netty/TyNettyTcpClient.java |
| | |
| | | |
| | | @Component |
| | | @Slf4j |
| | | public class TyNettyTcpClient { |
| | | public class NettyTcpClient { |
| | | |
| | | public static Map<String, TyBoxSession> channels = new HashMap<>(); |
| | | public static Map<String, TcpClientSession> channels = new HashMap<>(); |
| | | |
| | | EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); |
| | | |
| | |
| | | */ |
| | | public void initConnection(String host, Integer port) { |
| | | |
| | | log.info("初始化连接天宇tcp服务器【{}:{}】", host, port); |
| | | String currentBoxSn = ""; |
| | | log.info("初始化连接TCP服务器【{}:{}】", host, port); |
| | | String clientId = "clientId_1"; |
| | | //判断是否已经存在连接,如果存在则关闭之前的连接 |
| | | if (channels.containsKey(host + ":" + port)) { |
| | | currentBoxSn = channels.get(host + ":" + port).getSubBoxSn(); |
| | | clientId = channels.get(host + ":" + port).getClientId(); |
| | | channels.get(host + ":" + port).getChannelFuture().channel().close(); |
| | | } |
| | | |
| | |
| | | Bootstrap bootstrap = getBootstrap(); |
| | | ChannelFuture future = bootstrap.connect(host, port).addListener((ChannelFuture futureListener) -> { |
| | | if (futureListener.isSuccess()) { |
| | | log.info("连接天宇TCP服务器成功【{}:{}】", host, port); |
| | | log.info("连接TCP服务器成功【{}:{}】", host, port); |
| | | TyTcpServerCache.putTcpServerCache(host + ":" + port, true); |
| | | } else { |
| | | final EventLoop eventLoop = futureListener.channel().eventLoop(); |
| | | eventLoop.schedule(() -> { |
| | | log.info("连接天宇TCP服务器失败【{}:{}】,正尝试重连...", host, port); |
| | | log.info("连接TCP服务器失败【{}:{}】,正尝试重连...", host, port); |
| | | TyTcpServerCache.putTcpServerCache(host + ":" + port, false); |
| | | try { |
| | | initConnection(host, port); |
| | |
| | | } |
| | | }); |
| | | //将连接存入集合 |
| | | channels.put(host + ":" + port, TyBoxSession.builder().subBoxSn(currentBoxSn).channelFuture(future).isReConnect(!currentBoxSn.equals("")).build()); |
| | | channels.put(host + ":" + port, |
| | | TcpClientSession.builder().ClientId(clientId).channelFuture(future).isReConnect(!clientId.isEmpty()).build()); |
| | | } |
| | | |
| | | //创建天宇连接 |