package com.casic.missiles.client; import com.casic.missiles.core.HjtDecoder; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.Unpooled; 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.DelimiterBasedFrameDecoder; import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import org.springframework.beans.factory.annotation.Autowired; import java.net.InetSocketAddress; import java.util.concurrent.ConcurrentHashMap; public class NettyClient { private NioEventLoopGroup nioEventLoopGroup; private Channel channel; public boolean connectStatus = false; public void initNetty(String userId, String devIp,String host, int port) { //创建nioEventLoopGroup NioEventLoopGroup group = new NioEventLoopGroup(); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group).channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) //无阻塞 .option(ChannelOption.SO_KEEPALIVE, true)//长连接 .remoteAddress(new InetSocketAddress(host, port)) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new HjtDecoder()); ch.pipeline().addLast(new ClientHandler(userId,devIp)); } }); ChannelFuture channelFuture = null; try { // 发起连接 channelFuture = bootstrap.connect().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (channelFuture.isSuccess()) { connectStatus = true; channel = channelFuture.channel(); System.out.println("用户:" + userId + "->服务端连接成功..."); } else { System.out.println("用户:" + userId + "->服务端连接失败..."); connectStatus = false; } } }).sync(); // 等待连接关闭 // channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); connectStatus = false; } // finally { // connectStatus = false; // listener.onServiceStatusConnectChanged(Constant.STATUS_CONNECT_CLOSED); // if (null != channelFuture) { // if (channelFuture.channel() != null && channelFuture.channel().isOpen()) { // channelFuture.channel().close(); // } // } // group.shutdownGracefully(); //重新连接 // if (!connectStatus) // reconnect(userId, host, port); // } } //重新连接 private void reconnect(String userId, String devIp, String host, int port) { if (!connectStatus) { try { Thread.sleep(15000); System.out.println("connect ===> 重新连接TCP服务器"); initNetty(userId,devIp, host, port); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }