JLChen
2021-12-10 a37eca3ea9ad0d895ec8bb5af8c0d0b90da3169e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package com.hdl.sdk.socket;
 
import android.text.TextUtils;
import android.util.Log;
 
import androidx.collection.ArrayMap;
 
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.listener.SendListener;
 
import java.net.ConnectException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
 
/**
 * Created by Tong on 2021/9/26.
 * Tcp/Udp 启动器
 */
public class SocketBoot {
 
    private ExecutorService connectThread;
    private ScheduledExecutorService heartbeatThread;
    private ExecutorService sendThread;
    private ExecutorService receiveThread;
    private ScheduledExecutorService delayThread;
 
    private final IClient client;
 
    /**
     * socket是否在运行
     */
    private final AtomicBoolean isRun = new AtomicBoolean(false);
 
    private final AtomicBoolean isOpenRetry = new AtomicBoolean(false);
 
    private final AtomicInteger resendCount = new AtomicInteger(0);
 
    private final BlockingQueue<SocketRequest> mMessageQueue = new LinkedBlockingDeque<>();
 
    private final ArrayMap<String, SendListener> sendMap = new ArrayMap<>();
 
    public SocketBoot(IClient client) {
        this.client = client;
    }
 
    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();
                        }
                    }
                }
            });
        }
    }
 
    public 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("=====", "==发送数据==");
 
                        try {
                            SocketRequest socketRequest = mMessageQueue.take();
                            final String sendStr = new String(socketRequest.getData(), 0, socketRequest.getData().length);
                            LogUtils.d("=====", "==发送数据==:"+sendStr);
                            final String action = socketRequest.getAction();
                            try {
                                client.sendMsg(socketRequest.getData());
                                if (!TextUtils.isEmpty(action)) {
                                    SendListener sendListener = sendMap.get(action);
                                    if (sendListener != null) {
                                        sendListener.onSucceed();
                                    }
                                }
                            } catch (Exception e) {
                                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) {
 
                        }
 
                    }
 
                }
                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()) {
                        try {
                            //读取数据
                            client.onHandleResponse();
                        } catch (Exception e) {
                            e.printStackTrace();
                            LogUtils.d("====", "断开连接" + e.getMessage());
                            disconnectError();
                        }
                    }
                }
            }
        });
 
    }
 
 
    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);
                        }
                    }
                }
            }
        }, client.getOptions().getHeartbeatTimeInterval(), client.getOptions().getHeartbeatTimeInterval(), TimeUnit.MILLISECONDS);
    }
 
    public void stopHeartbeat() {
        if (heartbeatThread != null) {
            heartbeatThread.shutdownNow();
            heartbeatThread = null;
        }
    }
 
    public void sendMsg(byte[] msg) {
        sendMsg(msg, true, 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);
        }
        try {
            SocketRequest request = new SocketRequest(msg);
            if (listener != null && !TextUtils.isEmpty(request.getAction())) {
                sendMap.put(request.getAction(), listener);
            }
            mMessageQueue.put(request);
        } catch (InterruptedException ignored) {
 
        }
        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()) {
            client.disconnect();
            //断开连接
            client.onConnectStatus(ConnectStatus.DISCONNECT);
        }
    }
 
    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();
    }
}