-
Notifications
You must be signed in to change notification settings - Fork 144
/
WebSocketManager.java
410 lines (371 loc) · 12.2 KB
/
WebSocketManager.java
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
package com.zhangke.websocket;
import android.text.TextUtils;
import com.zhangke.websocket.dispatcher.MainThreadResponseDelivery;
import com.zhangke.websocket.dispatcher.ResponseDelivery;
import com.zhangke.websocket.dispatcher.ResponseProcessEngine;
import com.zhangke.websocket.request.Request;
import com.zhangke.websocket.request.RequestFactory;
import com.zhangke.websocket.response.ErrorResponse;
import com.zhangke.websocket.response.Response;
import com.zhangke.websocket.response.ResponseFactory;
import com.zhangke.websocket.util.LogUtil;
import org.java_websocket.framing.Framedata;
import org.java_websocket.framing.PingFrame;
import java.nio.ByteBuffer;
import java.util.Collection;
/**
* WebSocket 管理类
* <p>
* Created by ZhangKe on 2019/3/21.
*/
public class WebSocketManager {
private static final String TAG = "WSManager";
private WebSocketSetting mSetting;
private WebSocketWrapper mWebSocket;
/**
* 注册的监听器集合
*/
private ResponseDelivery mDelivery;
private ReconnectManager mReconnectManager;
private SocketWrapperListener mSocketWrapperListener;
/**
* 当前是否已销毁
*/
private boolean destroyed = false;
/**
* 用户调用了 disconnect 方法后为 true
*/
private boolean disconnect = false;
private WebSocketEngine mWebSocketEngine;
private ResponseProcessEngine mResponseProcessEngine;
WebSocketManager(WebSocketSetting setting,
WebSocketEngine webSocketEngine,
ResponseProcessEngine responseProcessEngine) {
this.mSetting = setting;
this.mWebSocketEngine = webSocketEngine;
this.mResponseProcessEngine = responseProcessEngine;
mDelivery = mSetting.getResponseDelivery();
if (mDelivery == null) {
mDelivery = new MainThreadResponseDelivery();
}
mSocketWrapperListener = getSocketWrapperListener();
if (mWebSocket == null) {
mWebSocket = new WebSocketWrapper(this.mSetting, mSocketWrapperListener);
}
start();
}
/**
* 启动,调用此方法开始连接
*/
public WebSocketManager start() {
if (mWebSocket == null) {
mWebSocket = new WebSocketWrapper(this.mSetting, mSocketWrapperListener);
}
if (mWebSocket.getConnectState() == 0) {
reconnect();
}
return this;
}
/**
* WebSocket 是否已连接
*/
public boolean isConnect() {
return mWebSocket != null && mWebSocket.getConnectState() == 2;
}
/**
* 设置重连管理类。
* 用户可根据需求设置自己的重连管理类,只需要实现接口即可
*/
public void setReconnectManager(ReconnectManager reconnectManager) {
this.mReconnectManager = reconnectManager;
}
/**
* 通过 {@link ReconnectManager} 开始重接
*/
public WebSocketManager reconnect() {
disconnect = false;
if (mReconnectManager == null) {
mReconnectManager = getDefaultReconnectManager();
}
if (!mReconnectManager.reconnecting()) {
mReconnectManager.startReconnect();
}
return this;
}
/**
* 使用新的 Setting 重新创建连接,同时会销毁之前的连接
*/
public WebSocketManager reconnect(WebSocketSetting setting) {
disconnect = false;
if (destroyed) {
LogUtil.e(TAG, "This WebSocketManager is destroyed!");
return this;
}
this.mSetting = setting;
if (mWebSocket != null) {
mWebSocket.destroy();
mWebSocket = null;
}
start();
return this;
}
/**
* 断开连接,断开后可使用 {@link this#reconnect()} 方法重新建立连接
*/
public WebSocketManager disConnect() {
disconnect = true;
if (destroyed) {
LogUtil.e(TAG, "This WebSocketManager is destroyed!");
return this;
}
if (mWebSocket.getConnectState() != 0) {
mWebSocketEngine.disConnect(mWebSocket, mSocketWrapperListener);
}
return this;
}
/**
* 发送文本数据
*/
public void send(String text) {
if (TextUtils.isEmpty(text)) {
return;
}
Request<String> request = RequestFactory.createStringRequest();
request.setRequestData(text);
sendRequest(request);
}
/**
* 发送 byte[] 数据
*/
public void send(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return;
}
Request<byte[]> request = RequestFactory.createByteArrayRequest();
request.setRequestData(bytes);
sendRequest(request);
}
/**
* 发送 ByteBuffer 数据
*/
public void send(ByteBuffer byteBuffer) {
if (byteBuffer == null) {
return;
}
Request<ByteBuffer> request = RequestFactory.createByteBufferRequest();
request.setRequestData(byteBuffer);
sendRequest(request);
}
/**
* 发送 Ping
*/
public void sendPing() {
sendRequest(RequestFactory.createPingRequest());
}
/**
* 发送 Pong
*/
public void sendPong() {
sendRequest(RequestFactory.createPongRequest());
}
/**
* 发送 Pong
*/
public void sendPong(PingFrame pingFrame) {
if (pingFrame == null) {
return;
}
Request<PingFrame> request = RequestFactory.createPongRequest();
request.setRequestData(pingFrame);
sendRequest(request);
}
/**
* 发送 {@link Framedata}
*/
public void sendFrame(Framedata framedata) {
if (framedata == null) {
return;
}
Request<Framedata> request = RequestFactory.createFrameDataRequest();
request.setRequestData(framedata);
sendRequest(request);
}
/**
* 发送 {@link Framedata} 集合
*/
public void sendFrame(Collection<Framedata> frameData) {
if (frameData == null) {
return;
}
Request<Collection<Framedata>> request = RequestFactory.createCollectionFrameRequest();
request.setRequestData(frameData);
sendRequest(request);
}
/**
* 添加一个监听器,使用完成之后需要调用
* {@link #removeListener(SocketListener)} 方法移除监听器
*/
public WebSocketManager addListener(SocketListener listener) {
mDelivery.addListener(listener);
return this;
}
/**
* 移除一个监听器
*/
public WebSocketManager removeListener(SocketListener listener) {
mDelivery.removeListener(listener);
return this;
}
/**
* 获取配置类,
* 部分参数支持动态设定。
*/
public WebSocketSetting getSetting() {
return mSetting;
}
/**
* 彻底销毁该连接,销毁后改连接完全失效,
* 请勿使用其他方法。
*/
public void destroy() {
destroyed = true;
if (mWebSocket != null) {
mWebSocketEngine.destroyWebSocket(mWebSocket);
mWebSocketEngine = null;
mWebSocket = null;
}
if (mDelivery != null) {
if (!mDelivery.isEmpty()) {
mDelivery.clear();
}
mDelivery = null;
}
if (mReconnectManager != null) {
if (mReconnectManager.reconnecting()) {
mReconnectManager.stopReconnect();
}
mReconnectManager = null;
}
}
/**
* 重新连接一次,
* for {@link ReconnectManager}
*/
void reconnectOnce() {
if (destroyed) {
LogUtil.e(TAG, "This WebSocketManager is destroyed!");
return;
}
if (mWebSocket.getConnectState() == 0) {
mWebSocketEngine.connect(mWebSocket, mSocketWrapperListener);
} else {
if (mReconnectManager != null) {
mReconnectManager.onConnected();
}
LogUtil.e(TAG, "WebSocket 已连接,请勿重试。");
}
}
/**
* 发送数据
*/
private void sendRequest(Request request) {
if (destroyed) {
LogUtil.e(TAG, "This WebSocketManager is destroyed!");
return;
}
mWebSocketEngine.sendRequest(mWebSocket, request, mSocketWrapperListener);
}
/**
* 获取默认的重连器
*/
private ReconnectManager getDefaultReconnectManager() {
return new DefaultReconnectManager(this, new ReconnectManager.OnConnectListener() {
@Override
public void onConnected() {
LogUtil.i(TAG, "重连成功");
}
@Override
public void onDisconnect() {
LogUtil.i(TAG, "重连失败");
mSetting.getResponseDispatcher()
.onDisconnect(mDelivery);
}
});
}
/**
* 获取监听器
*/
private SocketWrapperListener getSocketWrapperListener() {
return new SocketWrapperListener() {
@Override
public void onConnected() {
if (mReconnectManager != null) {
mReconnectManager.onConnected();
}
mSetting.getResponseDispatcher()
.onConnected(mDelivery);
}
@Override
public void onConnectFailed(Throwable e) {
//if reconnecting,interrupt this event for ReconnectManager.
if (mReconnectManager != null &&
mReconnectManager.reconnecting()) {
mReconnectManager.onConnectError(e);
}
mSetting.getResponseDispatcher()
.onConnectFailed(e, mDelivery);
}
@Override
public void onDisconnect() {
mSetting.getResponseDispatcher()
.onDisconnect(mDelivery);
if (mReconnectManager != null &&
mReconnectManager.reconnecting()) {
if (disconnect) {
mSetting.getResponseDispatcher()
.onDisconnect(mDelivery);
} else {
mReconnectManager.onConnectError(null);
}
} else {
if (!disconnect) {
if (mReconnectManager == null) {
mReconnectManager = getDefaultReconnectManager();
}
mReconnectManager.onConnectError(null);
mReconnectManager.startReconnect();
}
}
}
@Override
public void onSendDataError(Request request, int type, Throwable tr) {
ErrorResponse errorResponse = ResponseFactory.createErrorResponse();
errorResponse.init(request, type, tr);
if (mSetting.processDataOnBackground()) {
mResponseProcessEngine
.onSendDataError(errorResponse,
mSetting.getResponseDispatcher(),
mDelivery);
} else {
mSetting.getResponseDispatcher().onSendDataError(errorResponse, mDelivery);
}
if (!disconnect && type == ErrorResponse.ERROR_NO_CONNECT) {
LogUtil.e(TAG, "数据发送失败,网络未连接,开始重连。。。");
reconnect();
}
//todo 使用完注意释放资源 request.release();
}
@Override
public void onMessage(Response message) {
if (mSetting.processDataOnBackground()) {
mResponseProcessEngine
.onMessageReceive(message,
mSetting.getResponseDispatcher(),
mDelivery);
} else {
message.onResponse(mSetting.getResponseDispatcher(), mDelivery);
}
}
};
}
}