package com.mes.netty; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.string.StringEncoder; import java.util.concurrent.TimeUnit; import com.mes.ui.MesClient; public class NettyClient { public SocketChannel socketChannel; public ChannelFuture future; private static EventLoopGroup group; private static Bootstrap bootstrap; private volatile boolean connecting = false; private void ensureBootstrap() { if (group != null && !group.isShutdown()) { return; } group = new NioEventLoopGroup(); bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.SO_KEEPALIVE, true) .handler(new ChannelInitializer() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline() .addLast(new XDecoder()) .addLast(new StringEncoder()) .addLast(new NettyClientHandler()); } }) .remoteAddress(MesClient.mes_server_ip, MesClient.mes_tcp_port); } public void resetConnection() { connecting = false; future = null; socketChannel = null; } public boolean isChannelActive() { return future != null && future.channel() != null && future.channel().isActive(); } public void run(Object msg) { if (isChannelActive()) { future.channel().writeAndFlush(msg); return; } if (connecting) { if (group != null && !group.isShutdown()) { group.schedule(() -> run(msg), 300, TimeUnit.MILLISECONDS); } return; } connecting = true; ensureBootstrap(); System.out.println("客户端正在连接服务端..."); future = bootstrap.connect(); future.addListener((ChannelFutureListener) future1 -> { connecting = false; if (future1.isSuccess()) { MesClient.tcp_connect_flag = true; MesClient.connect_request_flag = false; System.out.println("连接Netty服务端成功"); future1.channel().writeAndFlush(msg); } else { MesClient.tcp_connect_flag = false; MesClient.connect_request_flag = true; System.out.println("连接失败,进行断线重连"); if (future1.channel() != null) { future1.channel().eventLoop().schedule(() -> run(msg), 10, TimeUnit.SECONDS); } else if (group != null) { group.schedule(() -> run(msg), 10, TimeUnit.SECONDS); } } MesClient.setTcpStatus(); }); socketChannel = (SocketChannel) future.channel(); } }