|
@@ -0,0 +1,69 @@
|
|
1
|
+package com.xhly.websocket.service;
|
|
2
|
+
|
|
3
|
+import android.util.Log;
|
|
4
|
+
|
|
5
|
+import com.neovisionaries.ws.client.WebSocket;
|
|
6
|
+import com.xhly.corelib.utils.GsonUtils;
|
|
7
|
+import com.xhly.websocket.bean.HertBean;
|
|
8
|
+
|
|
9
|
+import java.util.concurrent.ExecutorService;
|
|
10
|
+import java.util.concurrent.Executors;
|
|
11
|
+
|
|
12
|
+public class WebSocketHelper {
|
|
13
|
+
|
|
14
|
+ private static final WebSocketHelper ourInstance = new WebSocketHelper();
|
|
15
|
+ private final ExecutorService sendExecutor = Executors.newSingleThreadExecutor();
|
|
16
|
+ private WebSocket webSocket;
|
|
17
|
+
|
|
18
|
+ private WebSocketHelper() {
|
|
19
|
+ }
|
|
20
|
+
|
|
21
|
+ public static WebSocketHelper getInstance() {
|
|
22
|
+ return ourInstance;
|
|
23
|
+ }
|
|
24
|
+
|
|
25
|
+ public WebSocketHelper build(WebSocket webSocket) {
|
|
26
|
+ this.webSocket = webSocket;
|
|
27
|
+ return this;
|
|
28
|
+ }
|
|
29
|
+
|
|
30
|
+ /**
|
|
31
|
+ * @param type 发送不同的type获得socket内容
|
|
32
|
+ */
|
|
33
|
+ public void sendSocketType(String type) {
|
|
34
|
+ HertBean hertBean = new HertBean();
|
|
35
|
+ hertBean.setType(type);
|
|
36
|
+ String s = GsonUtils.parseClassToJson(hertBean);
|
|
37
|
+ send(webSocket, s);
|
|
38
|
+ }
|
|
39
|
+
|
|
40
|
+ public void sendSocketString(String s) {
|
|
41
|
+ send(webSocket, s);
|
|
42
|
+ }
|
|
43
|
+
|
|
44
|
+ /**
|
|
45
|
+ * @param webSocket
|
|
46
|
+ * @param id 心跳
|
|
47
|
+ */
|
|
48
|
+ public void hearBeat(WebSocket webSocket) {
|
|
49
|
+ HertBean hertBean = new HertBean();
|
|
50
|
+ hertBean.setType("ping");
|
|
51
|
+ String s = GsonUtils.parseClassToJson(hertBean);
|
|
52
|
+ send(webSocket, s);
|
|
53
|
+ }
|
|
54
|
+
|
|
55
|
+ private void send(final WebSocket webSocket, final String data) {
|
|
56
|
+ Log.v("socket", "socket 发送消息:" + data);
|
|
57
|
+ if (webSocket == null) {
|
|
58
|
+ return;
|
|
59
|
+ }
|
|
60
|
+ sendExecutor.execute(new Runnable() {
|
|
61
|
+ @Override
|
|
62
|
+ public void run() {
|
|
63
|
+ webSocket.sendText(data);
|
|
64
|
+ }
|
|
65
|
+ });
|
|
66
|
+ }
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+}
|