|
@@ -0,0 +1,370 @@
|
|
1
|
+package com.xhly.websocket.service;
|
|
2
|
+
|
|
3
|
+import android.content.Context;
|
|
4
|
+import android.os.Handler;
|
|
5
|
+import android.text.TextUtils;
|
|
6
|
+import android.util.Log;
|
|
7
|
+import android.widget.Toast;
|
|
8
|
+
|
|
9
|
+import com.neovisionaries.ws.client.WebSocket;
|
|
10
|
+import com.neovisionaries.ws.client.WebSocketAdapter;
|
|
11
|
+import com.neovisionaries.ws.client.WebSocketException;
|
|
12
|
+import com.neovisionaries.ws.client.WebSocketFactory;
|
|
13
|
+import com.neovisionaries.ws.client.WebSocketFrame;
|
|
14
|
+import com.xhly.corelib.utils.NetworkUtils;
|
|
15
|
+
|
|
16
|
+import java.io.IOException;
|
|
17
|
+import java.util.List;
|
|
18
|
+import java.util.Map;
|
|
19
|
+import java.util.concurrent.TimeUnit;
|
|
20
|
+
|
|
21
|
+import io.reactivex.Observable;
|
|
22
|
+import io.reactivex.Observer;
|
|
23
|
+import io.reactivex.android.schedulers.AndroidSchedulers;
|
|
24
|
+import io.reactivex.disposables.Disposable;
|
|
25
|
+import io.reactivex.schedulers.Schedulers;
|
|
26
|
+
|
|
27
|
+public abstract class SocketClient {
|
|
28
|
+ /**
|
|
29
|
+ * 聊天
|
|
30
|
+ */
|
|
31
|
+ protected static final int SOCKET_TYPE = 1;
|
|
32
|
+ /**
|
|
33
|
+ * WebSocket config
|
|
34
|
+ */
|
|
35
|
+ private static final int FRAME_QUEUE_SIZE = 5;
|
|
36
|
+ /**
|
|
37
|
+ * 心跳时间间隔单位是s
|
|
38
|
+ */
|
|
39
|
+ private static final long HEART_INTERVAL = 10;
|
|
40
|
+ /**
|
|
41
|
+ * 未收到心跳响应的次数
|
|
42
|
+ */
|
|
43
|
+ public static int HEART_NOT_RECEIVE_TIME = 0;
|
|
44
|
+ /**
|
|
45
|
+ * 是否收到心跳响应
|
|
46
|
+ */
|
|
47
|
+ public static boolean HAS_HEART_RECEIVE = false;
|
|
48
|
+ /**
|
|
49
|
+ * 连接超时时间,单位毫秒
|
|
50
|
+ */
|
|
51
|
+ public static int CONNECT_TIMEOUT = 20000;
|
|
52
|
+ public static boolean closeWebsocket = false;
|
|
53
|
+ public String TAG = LongConnService.class.getSimpleName();
|
|
54
|
+ protected int type = 1;
|
|
55
|
+ protected String connectUrl;
|
|
56
|
+ /**
|
|
57
|
+ * 重连最小时间间隔,单位毫秒
|
|
58
|
+ */
|
|
59
|
+ private long minInterval = 10000;
|
|
60
|
+ /**
|
|
61
|
+ * 重连最大时间间隔,单位毫秒
|
|
62
|
+ */
|
|
63
|
+ private long maxInterval = 60000;
|
|
64
|
+ private Handler mHandler = new Handler();
|
|
65
|
+ /**
|
|
66
|
+ * 重连次数
|
|
67
|
+ */
|
|
68
|
+ private int reconnectCount = 0;
|
|
69
|
+ /**
|
|
70
|
+ * 心跳subscription
|
|
71
|
+ */
|
|
72
|
+ private Disposable heartSubscription;
|
|
73
|
+ /**
|
|
74
|
+ * 是否连接状态
|
|
75
|
+ */
|
|
76
|
+ private boolean connected = false;
|
|
77
|
+ /**
|
|
78
|
+ * 是否允许重连
|
|
79
|
+ */
|
|
80
|
+ private boolean isReConnect = true;
|
|
81
|
+ private WsStatus mStatus;
|
|
82
|
+ private WebSocket webSocket;
|
|
83
|
+ private WsListener mListener;
|
|
84
|
+ //是否使用单项心跳
|
|
85
|
+ private boolean singleheartbeat = true;
|
|
86
|
+
|
|
87
|
+ protected Context context;
|
|
88
|
+ /**
|
|
89
|
+ * 设置已收到心跳
|
|
90
|
+ */
|
|
91
|
+ public static void hasReceiveHeart() {
|
|
92
|
+ HEART_NOT_RECEIVE_TIME = 0;
|
|
93
|
+ HAS_HEART_RECEIVE = true;
|
|
94
|
+ }
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+ public void startSocket(Context context) {
|
|
98
|
+ this.context=context;
|
|
99
|
+ Log.i(TAG, "startSocket............");
|
|
100
|
+ closeWebsocket = false;
|
|
101
|
+ if (mListener == null) {
|
|
102
|
+ mListener = new WsListener();
|
|
103
|
+ }
|
|
104
|
+ startConnect();
|
|
105
|
+ }
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+ public void onDestroy() {
|
|
109
|
+ Log.i(TAG, "onDestroy()............");
|
|
110
|
+ if (heartSubscription != null) {
|
|
111
|
+ heartSubscription.dispose();
|
|
112
|
+ }
|
|
113
|
+ disConnect();
|
|
114
|
+ closeWebsocket = true;
|
|
115
|
+ }
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+ /**
|
|
119
|
+ * 断开连接
|
|
120
|
+ */
|
|
121
|
+ private void disConnect() {
|
|
122
|
+ if (mHandler != null) {
|
|
123
|
+ mHandler.removeCallbacksAndMessages(null);
|
|
124
|
+ }
|
|
125
|
+ isReConnect = false;
|
|
126
|
+ connected = false;
|
|
127
|
+ if (webSocket != null) {
|
|
128
|
+ setStatus(WsStatus.DISCONNECT);
|
|
129
|
+ cancelReconnect();
|
|
130
|
+ webSocket.disconnect();
|
|
131
|
+ webSocket.clearListeners(); // 清除回调,避免多次链接导致上个链接的消息接收问题
|
|
132
|
+ webSocket = null;
|
|
133
|
+ }
|
|
134
|
+ }
|
|
135
|
+
|
|
136
|
+ /**
|
|
137
|
+ * 取消重连
|
|
138
|
+ */
|
|
139
|
+ private void cancelReconnect() {
|
|
140
|
+ reconnectCount = 0;
|
|
141
|
+ }
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+ /**
|
|
145
|
+ * 链接成功,子类可以拓展
|
|
146
|
+ */
|
|
147
|
+ public void onConnectedSuccess() {
|
|
148
|
+
|
|
149
|
+ }
|
|
150
|
+
|
|
151
|
+ /**
|
|
152
|
+ * 连接长链接
|
|
153
|
+ */
|
|
154
|
+ private synchronized void startConnect() {
|
|
155
|
+ if (TextUtils.isEmpty("用户ID")) {
|
|
156
|
+ setStatus(WsStatus.DISCONNECT);
|
|
157
|
+ return;
|
|
158
|
+ }
|
|
159
|
+ if (!NetworkUtils.isAvailable(context)) {
|
|
160
|
+ Toast.makeText(context, "网络不可用", Toast.LENGTH_SHORT);
|
|
161
|
+ return;
|
|
162
|
+ }
|
|
163
|
+
|
|
164
|
+ isReConnect = true;
|
|
165
|
+ /*
|
|
166
|
+ //存在!=null 并且open时断联的情况,所以注释
|
|
167
|
+ if (webSocket != null && webSocket.isOpen()) {
|
|
168
|
+ setStatus(WsStatus.CONNECT_SUCCESS);
|
|
169
|
+ return;
|
|
170
|
+ }*/
|
|
171
|
+ if (getStatus() == WsStatus.CONNECTING) {
|
|
172
|
+ return;
|
|
173
|
+ }
|
|
174
|
+
|
|
175
|
+ if (!connected) {
|
|
176
|
+ if (webSocket != null) {
|
|
177
|
+ webSocket.disconnect();
|
|
178
|
+ webSocket = null;
|
|
179
|
+ }
|
|
180
|
+ try {
|
|
181
|
+ Log.i(TAG, "第一次连接: " + connectUrl);
|
|
182
|
+ // 异步连接
|
|
183
|
+ webSocket = createWebSocket();
|
|
184
|
+ setStatus(WsStatus.CONNECTING);
|
|
185
|
+// checkConnectState();
|
|
186
|
+ } catch (IOException e) {
|
|
187
|
+ e.printStackTrace();
|
|
188
|
+ }
|
|
189
|
+ }
|
|
190
|
+ }
|
|
191
|
+
|
|
192
|
+ public WsStatus getStatus() {
|
|
193
|
+ return mStatus;
|
|
194
|
+ }
|
|
195
|
+
|
|
196
|
+ private void setStatus(WsStatus status) {
|
|
197
|
+ this.mStatus = status;
|
|
198
|
+ }
|
|
199
|
+
|
|
200
|
+ private WebSocket createWebSocket() throws IOException {
|
|
201
|
+ Log.i(TAG, "创建连接:createWebSocket()");
|
|
202
|
+ return new WebSocketFactory().createSocket(connectUrl, CONNECT_TIMEOUT)
|
|
203
|
+ //设置帧队列最大值为5
|
|
204
|
+ .setFrameQueueSize(FRAME_QUEUE_SIZE)
|
|
205
|
+ //设置不允许服务端关闭连接却未发送关闭帧
|
|
206
|
+ .setMissingCloseFrameAllowed(false)
|
|
207
|
+ //添加回调监听
|
|
208
|
+ .addListener(mListener).connectAsynchronously();
|
|
209
|
+ }
|
|
210
|
+
|
|
211
|
+ /**
|
|
212
|
+ * 重新连接
|
|
213
|
+ */
|
|
214
|
+ private void reConnect() {
|
|
215
|
+ if (!NetworkUtils.isAvailable(context)) {
|
|
216
|
+ reconnectCount = 0;
|
|
217
|
+ isReConnect = false;
|
|
218
|
+ closeWebsocket = true;
|
|
219
|
+ Log.i(TAG, "重连失败网络不可用,当前closeWebsocket==" + closeWebsocket);
|
|
220
|
+ return;
|
|
221
|
+ }
|
|
222
|
+ if (HAS_HEART_RECEIVE) {
|
|
223
|
+ return;
|
|
224
|
+ }
|
|
225
|
+ if (webSocket != null && !webSocket.isOpen() &&//当前连接断开了
|
|
226
|
+ getStatus() != WsStatus.CONNECTING && !connected) { //不是正在重连状态
|
|
227
|
+ setStatus(WsStatus.CONNECTING);
|
|
228
|
+ long reconnectTime = minInterval;
|
|
229
|
+ if (reconnectCount > 3) {
|
|
230
|
+ long temp = minInterval * (reconnectCount - 2);
|
|
231
|
+ reconnectTime = temp > maxInterval ? maxInterval : temp;
|
|
232
|
+ }
|
|
233
|
+ mHandler.postDelayed(new Runnable() {
|
|
234
|
+ @Override
|
|
235
|
+ public void run() {
|
|
236
|
+ try {
|
|
237
|
+ if (webSocket.isOpen() && isConnect()) {
|
|
238
|
+ return;
|
|
239
|
+ }
|
|
240
|
+ if (webSocket != null) {
|
|
241
|
+ webSocket.disconnect();
|
|
242
|
+ webSocket = null;
|
|
243
|
+ }
|
|
244
|
+ webSocket = createWebSocket();
|
|
245
|
+ reconnectCount++;
|
|
246
|
+ } catch (IOException e) {
|
|
247
|
+ e.printStackTrace();
|
|
248
|
+ }
|
|
249
|
+ }
|
|
250
|
+ }, reconnectTime);
|
|
251
|
+ }
|
|
252
|
+ }
|
|
253
|
+
|
|
254
|
+ /**
|
|
255
|
+ * 是否连接
|
|
256
|
+ */
|
|
257
|
+ private boolean isConnect() {
|
|
258
|
+ return connected;
|
|
259
|
+ }
|
|
260
|
+
|
|
261
|
+ /**
|
|
262
|
+ * 开始socket心跳
|
|
263
|
+ */
|
|
264
|
+ private void startHeartInterval(final WebSocket websocket) {
|
|
265
|
+ if (singleheartbeat) {
|
|
266
|
+ //单向心跳
|
|
267
|
+ WebSocketHelper.getInstance().hearBeat(websocket);
|
|
268
|
+ } else {
|
|
269
|
+ //双向心跳
|
|
270
|
+ if (HEART_NOT_RECEIVE_TIME > 3) {
|
|
271
|
+ // 有3次心跳没有收到服务器响应,则认为是已经断开连接,则重新连接
|
|
272
|
+ connected = false;
|
|
273
|
+ startConnect();
|
|
274
|
+ return;
|
|
275
|
+ }
|
|
276
|
+ // 在客户端上增加重试的逻辑。先发送心跳包,在N秒内若没有收到回复,则再发送一次。重试M次。
|
|
277
|
+ WebSocketHelper.getInstance().hearBeat(websocket);
|
|
278
|
+ HEART_NOT_RECEIVE_TIME++;
|
|
279
|
+ HAS_HEART_RECEIVE = false;
|
|
280
|
+ }
|
|
281
|
+ }
|
|
282
|
+
|
|
283
|
+ /**
|
|
284
|
+ * 处理socket响应消息
|
|
285
|
+ *
|
|
286
|
+ * @param text 要处理的文本
|
|
287
|
+ */
|
|
288
|
+ public abstract void processTextMessage(String text);
|
|
289
|
+
|
|
290
|
+ /**
|
|
291
|
+ * 继承默认的监听空实现WebSocketAdapter,重写我们需要的方法
|
|
292
|
+ * onTextMessage 收到文字信息
|
|
293
|
+ * onConnected 连接成功
|
|
294
|
+ * onConnectError 连接失败
|
|
295
|
+ * onDisconnected 连接关闭
|
|
296
|
+ */
|
|
297
|
+ private class WsListener extends WebSocketAdapter {
|
|
298
|
+ @Override
|
|
299
|
+ public void onConnected(final WebSocket websocket, Map<String, List<String>> headers) throws Exception {
|
|
300
|
+ super.onConnected(websocket, headers);
|
|
301
|
+ Log.i(TAG, "连接成功:" + headers.toString());
|
|
302
|
+ connected = true;
|
|
303
|
+ setStatus(WsStatus.CONNECT_SUCCESS);
|
|
304
|
+ cancelReconnect();// 连接成功的时候取消重连,初始化连接次数
|
|
305
|
+ if (type == SOCKET_TYPE) {
|
|
306
|
+ WebSocketHelper.getInstance().build(websocket);
|
|
307
|
+ //调用成功方法
|
|
308
|
+ onConnectedSuccess();
|
|
309
|
+ Observable.interval(HEART_INTERVAL, TimeUnit.SECONDS).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
|
|
310
|
+ @Override
|
|
311
|
+ public void onSubscribe(Disposable d) {
|
|
312
|
+ Log.d(TAG, "订阅开始");
|
|
313
|
+ heartSubscription = d;
|
|
314
|
+ }
|
|
315
|
+
|
|
316
|
+ @Override
|
|
317
|
+ public void onNext(Long aLong) {
|
|
318
|
+ Log.v(TAG, "发送心跳");
|
|
319
|
+ startHeartInterval(websocket);
|
|
320
|
+ }
|
|
321
|
+
|
|
322
|
+ @Override
|
|
323
|
+ public void onError(Throwable e) {
|
|
324
|
+
|
|
325
|
+ }
|
|
326
|
+
|
|
327
|
+ @Override
|
|
328
|
+ public void onComplete() {
|
|
329
|
+
|
|
330
|
+ }
|
|
331
|
+ });
|
|
332
|
+ }
|
|
333
|
+ }
|
|
334
|
+
|
|
335
|
+ @Override
|
|
336
|
+ public void onConnectError(WebSocket websocket, WebSocketException exception) throws Exception {
|
|
337
|
+ super.onConnectError(websocket, exception);
|
|
338
|
+ exception.printStackTrace();
|
|
339
|
+ Log.i(TAG, "连接错误: " + exception.getMessage());
|
|
340
|
+ HAS_HEART_RECEIVE = false;
|
|
341
|
+ setStatus(WsStatus.CONNECT_FAIL);
|
|
342
|
+ connected = false;
|
|
343
|
+ if (isReConnect) {
|
|
344
|
+ reConnect();//连接断开的时候调用重连方法
|
|
345
|
+ }
|
|
346
|
+ }
|
|
347
|
+
|
|
348
|
+ @Override
|
|
349
|
+ public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
|
|
350
|
+ super.onDisconnected(websocket, serverCloseFrame, clientCloseFrame, closedByServer);
|
|
351
|
+ Log.i(TAG, "断开连接,是否重连" + isReConnect + ",当前closeWebsocket==" + closeWebsocket);
|
|
352
|
+ HAS_HEART_RECEIVE = false;
|
|
353
|
+ connected = false;
|
|
354
|
+ if (heartSubscription != null) {
|
|
355
|
+ heartSubscription.dispose();
|
|
356
|
+ }
|
|
357
|
+ setStatus(WsStatus.CONNECT_FAIL);
|
|
358
|
+ if (isReConnect) {
|
|
359
|
+ reConnect();//连接断开的时候调用重连方法
|
|
360
|
+ }
|
|
361
|
+ }
|
|
362
|
+
|
|
363
|
+ @Override
|
|
364
|
+ public void onTextMessage(WebSocket websocket, String text) throws Exception {
|
|
365
|
+ super.onTextMessage(websocket, text);
|
|
366
|
+ hasReceiveHeart();
|
|
367
|
+ processTextMessage(text);
|
|
368
|
+ }
|
|
369
|
+ }
|
|
370
|
+}
|