wjc
2025-04-01 31e89a8697d049410c9d8d5c333cba33223bc9dc
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package com.hdl.sdk.link.socket;
 
import android.text.TextUtils;
 
import androidx.collection.ArrayMap;
 
import com.hdl.sdk.link.BuildConfig;
import com.hdl.sdk.link.HDLLinkLocalSdk;
import com.hdl.sdk.link.bean.LoginRequest;
import com.hdl.sdk.link.common.config.TopicConstant;
import com.hdl.sdk.link.common.utils.IdUtils;
import com.hdl.sdk.link.common.utils.LogUtils;
import com.hdl.sdk.link.common.utils.ThreadToolUtils;
import com.hdl.sdk.link.common.utils.gson.GsonConvert;
import com.hdl.sdk.link.core.bean.LinkRequest;
import com.hdl.sdk.link.core.bean.response.BaseLocalResponse;
import com.hdl.sdk.link.core.callback.HDLLinkCallBack;
import com.hdl.sdk.link.core.config.HDLLinkConfig;
import com.hdl.sdk.link.core.connect.HDLConnectHelper;
import com.hdl.sdk.link.socket.client.IClient;
import com.hdl.sdk.link.socket.client.IHeartbeat;
import com.hdl.sdk.link.socket.listener.SendListener;
import com.hdl.sdk.link.socket.annotation.ConnectStatus;
 
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
 
/**
 * Created by Tong on 2021/9/26.
 * Tcp/Udp 启动器
 */
public class TcpSocketBoot {
 
    private ExecutorService connectThread;
    private ExecutorService sendThread;
    private ExecutorService receiveThread;
    private ExecutorService heartbeatThread;
 
    private final IClient client;
    private IHeartbeat iHeartbeat;
    public void SetHeartbeat(IHeartbeat iHeartbeat){
        this.iHeartbeat=iHeartbeat;
    }
    /**
     * 当前接收到数据的时间
     */
    private  long time=System.currentTimeMillis();
    /**
     * tcp是否已经连接
     */
    private boolean connected=false;
 
    public IClient getClient() {
        return client;
    }
 
    public boolean isConnected() {
        return connected;
    }
 
    private final BlockingQueue<SocketRequest> mMessageQueue = new LinkedBlockingDeque<>();
 
    private final ArrayMap<String, SendListener> sendMap = new ArrayMap<>();
 
    public  TcpSocketBoot(IClient client) {
        TCP_SOCKET_BOOT_LIST.add(this);
        this.client = client;
        initConnectThread();
        initReceiveThread();
        initSendThread();
        initHeartbeat();
    }
 
    /**
     * 记录所有SocketBoot
     */
    final static List<TcpSocketBoot> TCP_SOCKET_BOOT_LIST = new ArrayList();
 
    /**
     * 根据IP地址及端口获取当前socketBoot
     * @param ipAddress
     * @param port
     * @return
     */
    public static TcpSocketBoot getByEndPoint(String ipAddress, int port){
        if(ipAddress==null){
            return  null;
        }
        for(TcpSocketBoot tcpSocketBoot : TCP_SOCKET_BOOT_LIST){
            if(ipAddress.equals(tcpSocketBoot.getClient().getOptions().getIp())&& tcpSocketBoot.getClient().getOptions().getPort()==port)
            {
                return tcpSocketBoot;
            }
        }
        return  null;
    }
 
    /**
     * 连接tcp,内部维护掉,可以不用开放外部,根据这个业务我特性处理好
     */
    private synchronized void connect() {
        try {
            LogUtils.i("TCP连接:"+this.getClient().getOptions().getIp());
            client.onConnectStatus(ConnectStatus.CONNECTING);
//            Thread.sleep(700);
            client.connect();
            LogUtils.i("TCP连接成功:"+this.getClient().getOptions().getIp());
            connected=true;
            tcpLogin("program", BuildConfig.SDKVersion);
            client.onConnectStatus(ConnectStatus.CONNECTED);
        }catch(Exception e) {
            LogUtils.e(e.getMessage());
        }
    }
 
    /**
     * tcp登录方便获取状态
     *
     * @param clientType 客户端类型
     *                   应用:app;
     *                   调试软件:program;
     *                   第三方:third_party;
     *                   网关:gateway;
     *                   其它:other
     * @param version    协议版本
     */
    public void tcpLogin(String clientType, String version) {
        final String msgId = IdUtils.getUUId();
        String time = String.valueOf(System.currentTimeMillis());
        final BaseLocalResponse<LoginRequest> data = new BaseLocalResponse<>();
        data.setId(msgId);
        data.setTime_stamp(time);
 
        final LoginRequest request = new LoginRequest();
        request.setVersion(version);
        request.setClientType(clientType);
 
        data.setObjects(request);
 
        String topic = String.format(TopicConstant.GATEWAY_LOGIN, HDLLinkConfig.getInstance().getGatewayId());
        LinkRequest messageRequest = new LinkRequest(topic,
                GsonConvert.getGson().toJson(data),false);
 
        new HDLConnectHelper(this.getClient().getOptions().getIp(),messageRequest,true).send();
    }
 
    /**
     * 初始化发送线程,只需要初始化一次
     */
    private void initSendThread() {
        if (sendThread == null) {
            sendThread = ThreadToolUtils.getInstance().newFixedThreadPool(1);
            sendThread.execute(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            if(connected==false){
                                Thread.sleep(100);
                                continue;
                            }
                            SocketRequest socketRequest = mMessageQueue.take();
                            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) {
                                connected = false;
                                LogUtils.e("发送失败:" + e.getMessage());
                                if (!TextUtils.isEmpty(action)) {
                                    SendListener sendListener = sendMap.get(action);
                                    if (sendListener != null) {
                                        sendListener.onError();
                                    }
                                }
                            }
                        } catch (Exception e) {
                            LogUtils.e("发送失败1:" + e.getMessage());
                        }
                    }
                }
            });
        }
    }
 
    /**
     * 初始化接收线程,只需要初始化一次
     */
    public void initReceiveThread() {
        if (receiveThread == null) {
            receiveThread = ThreadToolUtils.getInstance().newFixedThreadPool(1);
            receiveThread.execute(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            if (connected) {
                                //读取数据
                                client.onHandleResponse();
                                time= System.currentTimeMillis();
                            } else {
                                try {
                                    Thread.sleep(1000);
                                } catch (Exception ee) {
 
                                }
                            }
                        } catch (Exception e) {
                            connected = false;
                            LogUtils.e("接收数据线程异常" + e.getMessage());
                        }
                    }
                }
            });
        }
    }
 
    /**
     * 初始化重新连接线程
     */
    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(2*1000);
                        } catch (Exception e) {
 
                            LogUtils.e("定时连接线程异常:" + e.getMessage());
                        }
                    }
                }
            });
        }
    }
 
 
    /**
     * 初始化重新心跳线程
     */
    private void initHeartbeat() {
        if (heartbeatThread == null) {
            heartbeatThread = ThreadToolUtils.getInstance().newFixedThreadPool(1);
            heartbeatThread.execute(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            //5秒
                            if (connected && 5 * 1000 < (System.currentTimeMillis() - time)) {
                                time = System.currentTimeMillis();
                                //心跳检测
                                if (iHeartbeat != null)
                                    iHeartbeat.heartbeat();
                            }
                            Thread.sleep(10);
                        } catch (Exception e) {
                            LogUtils.e("定时心跳检测网关异常:" + e.getMessage());
                        }
                    }
                }
            });
        }
    }
    /**
     * 重新连接
     */
    private void reconect() {
        disconnect();
        connect();
    }
 
    /**
     * 发送无需回调
     * @param msg 发送的数据
     */
    public void sendMsg(byte[] msg) {
        sendMsg(msg, null);
    }
 
 
    /**
     * @param listener 一般情况无需监听
     */
    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 (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 关闭连接
     */
    private synchronized void disconnect() {
        try {
            client.disconnect();
            //断开连接
            client.onConnectStatus(ConnectStatus.DISCONNECT);
        } catch (Exception e) {
 
        }
    }
 
 
//    /**
//     * 断开全部的Link网关连接
//     */
//    public static void stopAllConnectLinkGateway() {
//        for (TcpSocketBoot data : TCP_SOCKET_BOOT_LIST) {
//            //断开指定的link网关连接
//            stopConnectLinkGateway(data);
//        }
//
//    }
//
//    /**
//     * 断开指定的link网关连接
//     *
//     * @param tcpSocketBoot tcp对象
//     */
//    public static void stopConnectLinkGateway(TcpSocketBoot tcpSocketBoot) {
//        synchronized (TCP_SOCKET_BOOT_LIST) {
//            try {
//                TCP_SOCKET_BOOT_LIST.remove(tcpSocketBoot);
//                tcpSocketBoot.client.disconnect();
//            } catch (Exception ignored) {
//            }
//        }
//    }
 
}