From cc6023291bc94a229b53d7c2d83bf2b39bbfa9a0 Mon Sep 17 00:00:00 2001
From: hxb <hxb@hdlchina.com.cn>
Date: 星期日, 27 三月 2022 21:27:29 +0800
Subject: [PATCH] 华尔思线上版本库

---
 HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/SocketBoot.java |  355 +++++++++++++++++++++++-----------------------------------
 1 files changed, 142 insertions(+), 213 deletions(-)

diff --git a/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/SocketBoot.java b/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/SocketBoot.java
index ac8ec9e..92f8f84 100644
--- a/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/SocketBoot.java
+++ b/HDLSDK/hdl-socket/src/main/java/com/hdl/sdk/socket/SocketBoot.java
@@ -5,13 +5,18 @@
 
 import androidx.collection.ArrayMap;
 
+import com.google.gson.JsonObject;
+import com.hdl.sdk.common.config.TopicConstant;
+import com.hdl.sdk.common.utils.IdUtils;
 import com.hdl.sdk.common.utils.LogUtils;
 import com.hdl.sdk.common.utils.ThreadToolUtils;
 import com.hdl.sdk.socket.annotation.ConnectStatus;
 import com.hdl.sdk.socket.client.IClient;
+import com.hdl.sdk.socket.client.IHeartbeat;
 import com.hdl.sdk.socket.listener.SendListener;
 
 import java.net.ConnectException;
+import java.util.Date;
 import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.LinkedBlockingDeque;
@@ -27,21 +32,28 @@
 public class SocketBoot {
 
     private ExecutorService connectThread;
-    private ScheduledExecutorService heartbeatThread;
     private ExecutorService sendThread;
     private ExecutorService receiveThread;
-    private ScheduledExecutorService delayThread;
+    private ExecutorService heartbeatThread;
 
     private final IClient client;
+    private IHeartbeat iHeartbeat;
+    public void SetHeartbeat(IHeartbeat iHeartbeat){
+        this.iHeartbeat=iHeartbeat;
+    }
+    /**
+     * 褰撳墠鎺ユ敹鍒版暟鎹殑鏃堕棿
+     */
+    private static long time=System.currentTimeMillis();
 
     /**
-     * socket鏄惁鍦ㄨ繍琛�
+     * tcp鏄惁宸茬粡杩炴帴
      */
-    private final AtomicBoolean isRun = new AtomicBoolean(false);
+    private boolean connected=false;
 
-    private final AtomicBoolean isOpenRetry = new AtomicBoolean(false);
-
-    private final AtomicInteger resendCount = new AtomicInteger(0);
+    public IClient getClient() {
+        return client;
+    }
 
     private final BlockingQueue<SocketRequest> mMessageQueue = new LinkedBlockingDeque<>();
 
@@ -49,90 +61,44 @@
 
     public SocketBoot(IClient client) {
         this.client = client;
+        initConnectThread();
+        initReceiveThread();
+        initSendThread();
+        initHeartbeat();
     }
 
-    public ScheduledExecutorService getHeartBeat() {
-        if (heartbeatThread == null) {
-            heartbeatThread = ThreadToolUtils.getInstance().newScheduledThreadPool(1);
-        }
-        return heartbeatThread;
-    }
-
-    public void connect() {
-        resendCount.set(0);
-        resetConnect(true);
-        isOpenRetry.set(true);
-    }
-
-    public synchronized void resetConnect(boolean isFirst) {
-        final int maxRetry = client.getOptions().getMaxRetry();
-        if (maxRetry == 0 && resendCount.get() > 0 ||
-                (maxRetry > 0 && maxRetry + 1 < resendCount.get())) {
-            LogUtils.d("====", "===閲嶈繛娆℃暟杈惧埌鏈�澶�==");
-            return;
-        }
-        if (!client.isConnect()) {
-            if (connectThread == null) {
-                connectThread = ThreadToolUtils.getInstance().newFixedThreadPool(1);
-            }
-            connectThread.execute(new Runnable() {
-                @Override
-                public void run() {
-                    client.onConnectStatus(ConnectStatus.CONNECTING);
-                    if (!isFirst) {
-                        try {
-                            resendCount.set(resendCount.get() + 1);
-                            Thread.sleep(300L);
-                            LogUtils.d("====", "==閲嶈繛绗�" + resendCount + "娆�==");
-                        } catch (Exception ignored) {
-                        }
-                    }
-                    try {
-                        client.connect();
-                        isRun.set(true);
-                        if (client.isConnect()) {
-                            LogUtils.d("====", "====杩炴帴鎴愬姛====");
-                            startHeartbeat();
-
-                            initSendThread();
-                            initReceiveThread();
-
-                            client.onConnectStatus(ConnectStatus.CONNECTED);
-                            resendCount.set(0);
-                        } else {
-                            throw new ConnectException();
-                        }
-                    } catch (Exception e) {
-                        e.printStackTrace();
-                        LogUtils.d("====", "===杩炴帴澶辫触===" + e);
-                        //鍐嶅垽鏂竴涓嬫湁娌℃湁杩炴帴
-                        if (!client.isConnect()) {
-                            isRun.set(false);
-                            client.onConnectStatus(ConnectStatus.DISCONNECT);
-                            stopHeartbeat();
-                            disconnectError();
-                        }
-                    }
-                }
-            });
+    /**
+     * 杩炴帴tcp锛屽唴閮ㄧ淮鎶ゆ帀锛屽彲浠ヤ笉鐢ㄥ紑鏀惧閮紝鏍规嵁杩欎釜涓氬姟鎴戠壒鎬у鐞嗗ソ
+     */
+    private synchronized void connect() {
+        try {
+            LogUtils.i("TCP杩炴帴");
+            client.onConnectStatus(ConnectStatus.CONNECTING);
+            Thread.sleep(1000);
+            client.connect();
+            connected=true;
+            LogUtils.i("TCP杩炴帴鎴愬姛");
+            client.onConnectStatus(ConnectStatus.CONNECTED);
+        }catch(Exception e) {
+            LogUtils.e("杩炴帴寮傚父"+e.getMessage());
         }
     }
 
-    public void initSendThread() {
+
+    /**
+     * 鍒濆鍖栧彂閫佺嚎绋嬶紝鍙渶瑕佸垵濮嬪寲涓�娆�
+     */
+    private void initSendThread() {
         if (sendThread == null) {
             sendThread = ThreadToolUtils.getInstance().newFixedThreadPool(1);
-        }
-        sendThread.execute(new Runnable() {
-            @Override
-            public void run() {
-                while (isRun.get()) {
-                    if (client.isConnect()) {
-                        LogUtils.d("=====", "==鍙戦�佹暟鎹�==");
-
+            sendThread.execute(new Runnable() {
+                @Override
+                public void run() {
+                    while (true) {
                         try {
                             SocketRequest socketRequest = mMessageQueue.take();
-                            final String sendStr = new String(socketRequest.getData(), 0, socketRequest.getData().length);
-                            LogUtils.d("=====", "==鍙戦�佹暟鎹�==锛�"+sendStr);
+//                            final String sendStr = new String(socketRequest.getData(), 0, socketRequest.getData().length);
+//                            LogUtils.i("鍙戦�佹暟鎹細" + sendStr);
                             final String action = socketRequest.getAction();
                             try {
                                 client.sendMsg(socketRequest.getData());
@@ -143,189 +109,152 @@
                                     }
                                 }
                             } catch (Exception e) {
+                                connected = false;
+                                LogUtils.e("鍙戦�佸け璐�:" + e.getMessage());
                                 if (!TextUtils.isEmpty(action)) {
                                     SendListener sendListener = sendMap.get(action);
                                     if (sendListener != null) {
                                         sendListener.onError();
                                     }
                                 }
-
-                                stopHeartbeat();
-                                if (sendThread != null) {
-                                    sendThread.shutdownNow();
-                                }
-                                if (isRun.get()) {
-                                    disconnectError();
-                                }
-
                             }
-                        } catch (InterruptedException ignored) {
+                        } catch (Exception e) {
 
                         }
-
                     }
-
                 }
-                LogUtils.d("=====", "==鍙戦�佺嚎绋嬪叧闂�==");
-            }
-        });
-
+            });
+        }
     }
 
+    /**
+     * 鍒濆鍖栨帴鏀剁嚎绋嬶紝鍙渶瑕佸垵濮嬪寲涓�娆�
+     */
     public void initReceiveThread() {
         if (receiveThread == null) {
             receiveThread = ThreadToolUtils.getInstance().newFixedThreadPool(1);
-        }
-        receiveThread.execute(new Runnable() {
-            @Override
-            public void run() {
-                while (isRun.get()) {
-                    if (client.isConnect()) {
+            receiveThread.execute(new Runnable() {
+                @Override
+                public void run() {
+                    while (true) {
                         try {
-                            //璇诲彇鏁版嵁
-                            client.onHandleResponse();
+                            if (connected) {
+                                //璇诲彇鏁版嵁
+                                client.onHandleResponse();
+                                time= System.currentTimeMillis();
+                            } else {
+                                try {
+                                    Thread.sleep(1000);
+                                } catch (Exception ee) {
+
+                                }
+                            }
                         } catch (Exception e) {
-                            e.printStackTrace();
-                            LogUtils.d("====", "鏂紑杩炴帴" + e.getMessage());
-                            disconnectError();
+                            connected = false;
+                            LogUtils.e("鎺ユ敹鏁版嵁绾跨▼寮傚父" + e.getMessage());
                         }
                     }
                 }
-            }
-        });
-
+            });
+        }
     }
 
-
-    public void startHeartbeat() {
-        if (heartbeatThread != null) {
-            heartbeatThread.shutdownNow();
-            heartbeatThread = null;
-        }
-        if (client.getOptions() == null || client.getOptions().getHeartbeatTimeInterval() <= 0 || !client.getOptions().isEnabledHeartbeat()) {
-            return;
-        }
-        getHeartBeat().scheduleWithFixedDelay(new Runnable() {
-            @Override
-            public void run() {
-                if (isRun.get()) {
-                    LogUtils.d("====", "===鍙戦�佸績璺冲寘===");
-                    if (client.getOptions() != null) {
-                        final byte[] heartBeat = client.getOptions().getHeartbeatData();
-                        if (heartBeat != null) {
-                            sendMsg(heartBeat, false, null);
-                        } else {
-                            sendMsg(new byte[0], false, null);
+    /**
+     * 鍒濆鍖栭噸鏂拌繛鎺ョ嚎绋�
+     */
+    private void initConnectThread() {
+        if (connectThread == null) {
+            connectThread = ThreadToolUtils.getInstance().newFixedThreadPool(1);
+            //涓�瀹氭椂闂存娴嬩竴娆¤繛鎺ユ儏鍐碉紝娌℃湁杩炴帴灏辨墽琛岃繛鎺ワ紝杩炴帴缁熶竴鐢辫繖閲岀淮鎶�
+            connectThread.execute(new Runnable() {
+                @Override
+                public void run() {
+                    while (true) {
+                        try {
+                            if (!connected) {
+                                reconect();
+                            }
+                            Thread.sleep(3*1000);
+                        } catch (Exception e) {
+                            LogUtils.e("瀹氭椂杩炴帴澶辫触:" + e.getMessage());
                         }
                     }
                 }
-            }
-        }, client.getOptions().getHeartbeatTimeInterval(), client.getOptions().getHeartbeatTimeInterval(), TimeUnit.MILLISECONDS);
-    }
-
-    public void stopHeartbeat() {
-        if (heartbeatThread != null) {
-            heartbeatThread.shutdownNow();
-            heartbeatThread = null;
+            });
         }
     }
 
+    /**
+     * 鍒濆鍖栭噸鏂板績璺崇嚎绋�
+     */
+    private void initHeartbeat() {
+        if (heartbeatThread == null) {
+            heartbeatThread = ThreadToolUtils.getInstance().newFixedThreadPool(1);
+            heartbeatThread.execute(new Runnable() {
+                @Override
+                public void run() {
+                    while (true) {
+                        try {
+                            //10绉�
+                            if (connected && 10 * 1000 < (System.currentTimeMillis() - time)) {
+                                time = System.currentTimeMillis();
+                                //蹇冭烦妫�娴�
+                                if (iHeartbeat != null)
+                                    iHeartbeat.heartbeat();
+                            }
+                            Thread.sleep(1000);
+                        } catch (Exception e) {
+                            LogUtils.e("瀹氭椂蹇冭烦妫�娴嬬綉鍏冲紓甯革細" + e.getMessage());
+                        }
+                    }
+                }
+            });
+        }
+    }
+
+
+    /**
+     * 閲嶆柊杩炴帴
+     */
+    private void reconect() {
+        disconnect();
+        connect();
+    }
+
+    /**
+     * 鍙戦�佹棤闇�鍥炶皟
+     * @param msg 鍙戦�佺殑鏁版嵁
+     */
     public void sendMsg(byte[] msg) {
-        sendMsg(msg, true, null);
+        sendMsg(msg, null);
     }
 
-    public void sendMsg(byte[] msg, SendListener listener) {
-        sendMsg(msg, true, listener);
-    }
 
     /**
      * @param listener 涓�鑸儏鍐垫棤闇�鐩戝惉
      */
-    private void sendMsg(byte[] msg, boolean isRefreshRetry, SendListener listener) {
-        if (isRefreshRetry) {
-            //閲嶇疆杩炴帴娆℃暟
-            resendCount.set(0);
-        }
+    public void sendMsg(byte[] msg, SendListener listener) {
         try {
             SocketRequest request = new SocketRequest(msg);
             if (listener != null && !TextUtils.isEmpty(request.getAction())) {
                 sendMap.put(request.getAction(), listener);
             }
             mMessageQueue.put(request);
-        } catch (InterruptedException ignored) {
-
+        } catch (Exception e) {
+            LogUtils.e("鍙戦�佹暟鎹け璐ワ細" + e.getMessage());
         }
-        if (!client.isConnect()) {
-            resetConnect(false);
-        }
-
     }
 
     /**
-     * 鍙戠敓閿欒锛岄噸杩�
+     * 鍏抽棴杩炴帴
      */
-    private void disconnectError() {
-        disconnect();
-        isRun.set(false);
-        if (isOpenRetry.get()) {
-            if (delayThread != null) {
-                delayThread.shutdownNow();
-            }
-            delayThread = ThreadToolUtils.getInstance().newScheduledThreadPool(1);
-            delayThread.schedule(new Runnable() {
-                @Override
-                public void run() {
-                    if (!client.isConnect() && isOpenRetry.get()) {
-                        resetConnect(false);
-                    }
-
-                }
-            }, 3000, TimeUnit.MILLISECONDS);
-        }
-
-    }
-
     private synchronized void disconnect() {
-        if (client.isConnect()) {
+        try {
             client.disconnect();
             //鏂紑杩炴帴
             client.onConnectStatus(ConnectStatus.DISCONNECT);
-        }
-    }
+        } catch (Exception e) {
 
-    public synchronized void close() {
-        isOpenRetry.set(false);
-        isRun.set(false);
-        if (connectThread != null) {
-            connectThread.shutdownNow();
-            connectThread = null;
         }
-        if (heartbeatThread != null) {
-            heartbeatThread.shutdownNow();
-            heartbeatThread = null;
-        }
-        if (sendThread != null) {
-            sendThread.shutdownNow();
-            sendThread = null;
-        }
-        if (receiveThread != null) {
-            receiveThread.shutdownNow();
-            receiveThread = null;
-        }
-        sendMap.clear();
-        client.disconnect();
-        mMessageQueue.clear();
-
-    }
-
-    public synchronized void release() {
-        close();
-        if (client != null && client.getOptions() != null) {
-            client.getOptions().clearConnectStatusListener();
-        }
-    }
-
-    public boolean isConnect() {
-        return client.isConnect();
     }
 }

--
Gitblit v1.8.0