瀏覽代碼

防止多个tcp连接

weizhengliang 3 年之前
父節點
當前提交
373c0a4e9c

+ 11 - 9
middleware/src/main/code/com/wdkl/ncs/android/middleware/tcp/TcpClient.java

@@ -43,6 +43,7 @@ public class TcpClient {
     private Integer reconnetTimes = 0;
     private Integer reconnetTimes = 0;
     //tcp是否完成初始化
     //tcp是否完成初始化
     private boolean inited = false;
     private boolean inited = false;
+    private boolean connecting = false;
 
 
 
 
     //单例
     //单例
@@ -92,15 +93,23 @@ public class TcpClient {
             return;
             return;
         }
         }
 
 
-        if (channel != null && channel.isActive()){
+        if (channel != null && (channel.isActive() || channel.isOpen())) {
             System.out.println("TcpClient connecting");
             System.out.println("TcpClient connecting");
             return;
             return;
         }
         }
 
 
+        //正在连接
+        if (connecting || Constant.TCP_CONNECTED) {
+            System.out.println("tcp is connecting or connected");
+            return;
+        }
+        connecting = true;
+
         System.out.println("connect start");
         System.out.println("connect start");
         ChannelFuture future = bootstrap.connect().addListener(new ChannelFutureListener() {
         ChannelFuture future = bootstrap.connect().addListener(new ChannelFutureListener() {
             @Override
             @Override
             public void operationComplete(ChannelFuture channelFuture) throws Exception {
             public void operationComplete(ChannelFuture channelFuture) throws Exception {
+                connecting = false;
                 if (channelFuture.isSuccess()){
                 if (channelFuture.isSuccess()){
                     isRunning = true;
                     isRunning = true;
                     channel = channelFuture.channel();
                     channel = channelFuture.channel();
@@ -110,17 +119,11 @@ public class TcpClient {
                     //连接失败时的处理
                     //连接失败时的处理
                     isRunning = false;
                     isRunning = false;
                     System.out.println("connect retry : " + retryTimes);
                     System.out.println("connect retry : " + retryTimes);
-                    //EventBus.getDefault().post(new MessageEvent(0, Constant.EVENT_TCP_STATE));
                     channelFuture.channel().eventLoop().schedule(new Runnable() {
                     channelFuture.channel().eventLoop().schedule(new Runnable() {
                         @Override
                         @Override
                         public void run() {
                         public void run() {
                             retryTimes++;
                             retryTimes++;
                             if (retryTimes > 30) { //重试30次还没连成功,等10分钟后再试
                             if (retryTimes > 30) { //重试30次还没连成功,等10分钟后再试
-//                                System.out.println("TcpClient 重试" + (retryTimes - 1) + "次,结束");
-//                                channel.close();
-//                                workGroup.shutdownGracefully();
-//                                //todo: 从API获取新的serverIP和serverPort,全新连接
-//                                TcpClient.getInstance().init(Constant.TCP_SERVER_URL, Constant.TCP_PORT, Constant.TCP_HEART_BEAT);
                                 retryTimes=1;
                                 retryTimes=1;
                                 reconnetTimes++;
                                 reconnetTimes++;
                                 channelFuture.channel().eventLoop().schedule(new Runnable() {
                                 channelFuture.channel().eventLoop().schedule(new Runnable() {
@@ -133,8 +136,7 @@ public class TcpClient {
                                             doConnect();
                                             doConnect();
                                         }
                                         }
                                     }
                                     }
-                                }, 60*5, TimeUnit.SECONDS);
-
+                                }, 60*2, TimeUnit.SECONDS);
                             }else{
                             }else{
                                 doConnect();
                                 doConnect();
                             }
                             }

+ 1 - 47
middleware/src/main/code/com/wdkl/ncs/android/middleware/tcp/TcpClientHandler.java

@@ -57,13 +57,11 @@ public class TcpClientHandler extends SimpleChannelInboundHandler<String> {
         EventBus.getDefault().post(new MessageEvent(0, Constant.EVENT_TCP_STATE));
         EventBus.getDefault().post(new MessageEvent(0, Constant.EVENT_TCP_STATE));
         Log.i(TAG, "失去连接");
         Log.i(TAG, "失去连接");
         TcpClient.getInstance().doConnect();
         TcpClient.getInstance().doConnect();
-        //reConnect(ctx);
     }
     }
 
 
     //读取String消息
     //读取String消息
     @Override
     @Override
     protected void channelRead0(ChannelHandlerContext ctx, String source) throws Exception {
     protected void channelRead0(ChannelHandlerContext ctx, String source) throws Exception {
-        //System.out.println("channelRead0: read callback from server ===> " + source);
         if(source.equals("1")){
         if(source.equals("1")){
             Log.i(TAG,"收到服务器返回的心跳 "+source);
             Log.i(TAG,"收到服务器返回的心跳 "+source);
         }else {
         }else {
@@ -87,13 +85,10 @@ public class TcpClientHandler extends SimpleChannelInboundHandler<String> {
             if (event.state() == IdleState.WRITER_IDLE) { //超时未执行写操作,在指定的超时时间内未有写操作,要发送心跳包,告诉服务器连接还存活。服务器收到心跳立马回应,正常客户端收到后执行读操作,
             if (event.state() == IdleState.WRITER_IDLE) { //超时未执行写操作,在指定的超时时间内未有写操作,要发送心跳包,告诉服务器连接还存活。服务器收到心跳立马回应,正常客户端收到后执行读操作,
                 ctx.writeAndFlush("0");                //这种情况下不会引发READER_IDLE事件。如果服务器因为网络或其他原因导致回应的心跳,客户端没有收到,在超过写超时时间2个周期后依然没有收到,
                 ctx.writeAndFlush("0");                //这种情况下不会引发READER_IDLE事件。如果服务器因为网络或其他原因导致回应的心跳,客户端没有收到,在超过写超时时间2个周期后依然没有收到,
             } else if (event.state() == IdleState.READER_IDLE) { //认为服务不可用,主动断开连接
             } else if (event.state() == IdleState.READER_IDLE) { //认为服务不可用,主动断开连接
-//                ctx.channel().close();
                 Log.i(TAG, "TcpClientHandler ===> READER_IDLE");
                 Log.i(TAG, "TcpClientHandler ===> READER_IDLE");
                 ctx.close();
                 ctx.close();
-//                ctx.close();
             } else if (event.state() == IdleState.ALL_IDLE) {
             } else if (event.state() == IdleState.ALL_IDLE) {
                 Log.i(TAG, "TcpClientHandler ===> ALL_IDLE");
                 Log.i(TAG, "TcpClientHandler ===> ALL_IDLE");
-
             }
             }
         }
         }
     }
     }
@@ -112,50 +107,9 @@ public class TcpClientHandler extends SimpleChannelInboundHandler<String> {
     public void sendMsg(String msg){
     public void sendMsg(String msg){
         if (ctx==null){
         if (ctx==null){
             System.out.println("ctx is null");
             System.out.println("ctx is null");
-            /*try {
-                Thread.sleep(1000);
-                sendMsg(msg);
-            } catch (InterruptedException e) {
-                e.printStackTrace();
-            }*/
             return;
             return;
         }
         }
-        System.out.println("wzlll: tcp msg====" + msg);
+        System.out.println("send tcp msg====" + msg);
         ctx.writeAndFlush(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));
         ctx.writeAndFlush(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));
     }
     }
-
-    //已经连接上,中途失去连接时的处理
-    private void reConnect(final ChannelHandlerContext ctx){
-        if (totalRetryTimes>100){
-            //todo: 存储数据库,并告警
-        }
-        if (connected && (TcpClient.getInstance().channel != null && TcpClient.getInstance().channel.isActive())){
-            return;
-        }
-        totalRetryTimes++;
-        System.out.println("TcpClientHandler 总计连接次数:"+totalRetryTimes);
-        retryTimes++;
-        if (retryTimes > 30) { //超时30次,10分钟后再试
-            retryTimes = 0;
-            ctx.channel().eventLoop().schedule(new Runnable() {
-                @Override
-                public void run() {
-                    System.out.println("TcpClientHandler 重新连接,第" + retryTimes + "次");
-                    TcpClient.getInstance().doConnect();
-                    reConnect(ctx);
-                }
-            }, 10*60, TimeUnit.SECONDS);
-
-
-        }else {
-            ctx.channel().eventLoop().schedule(new Runnable() {
-                @Override
-                public void run() {
-                    System.out.println("TcpClientHandler 重新连接,第" + retryTimes + "次");
-                    TcpClient.getInstance().doConnect();
-                    reConnect(ctx);
-                }
-            }, retrySeconds * retryTimes, TimeUnit.SECONDS);
-        }
-    }
 }
 }