hxb
2022-02-16 845bb16392e6b47ec31147d0e7c6ddc39537f2e7
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
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 ExecutorService sendThread;
    private ExecutorService receiveThread;
 
    private final IClient client;
 
    /**
     * tcp是否已经连接
     */
    private boolean connected=false;
 
    public IClient getClient() {
        return client;
    }
 
    private final BlockingQueue<SocketRequest> mMessageQueue = new LinkedBlockingDeque<>();
 
    private final ArrayMap<String, SendListener> sendMap = new ArrayMap<>();
 
    public SocketBoot(IClient client) {
        this.client = client;
        initConnectThread();
        initReceiveThread();
        initSendThread();
    }
 
    /**
     * 连接tcp,内部维护掉,可以不用开放外部,根据这个业务我特性处理好
     */
    private synchronized void connect() {
        try {
            LogUtils.i("TCP连接");
            client.onConnectStatus(ConnectStatus.CONNECTING);
            Thread.sleep(700);
            client.connect();
            connected=true;
            client.onConnectStatus(ConnectStatus.CONNECTED);
        }catch(Exception e) {
            LogUtils.e("连接异常"+e.getMessage());
        }
    }
 
 
    /**
     * 初始化发送线程,只需要初始化一次
     */
    private void initSendThread() {
        if (sendThread == null) {
            sendThread = ThreadToolUtils.getInstance().newFixedThreadPool(1);
            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.i("发送数据:" + 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) {
                                connected = false;
                                LogUtils.e("发送失败:" + e.getMessage());
                                if (!TextUtils.isEmpty(action)) {
                                    SendListener sendListener = sendMap.get(action);
                                    if (sendListener != null) {
                                        sendListener.onError();
                                    }
                                }
                            }
                        } catch (Exception e) {
 
                        }
                    }
                }
            });
        }
    }
 
    /**
     * 初始化接收线程,只需要初始化一次
     */
    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();
                            } 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(10*1000);
                        } catch (Exception e) {
 
                        }
                    }
                }
            });
        }
    }
    /**
     * 重新连接
     */
    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) {
 
        }
    }
 
    /**
     * 关闭连接
     */
    private synchronized void disconnect() {
        try {
            client.disconnect();
            //断开连接
            client.onConnectStatus(ConnectStatus.DISCONNECT);
        } catch (Exception e) {
 
        }
    }
}