Просмотр исходного кода

1.添加发送单向心跳功能。

master
wangwanlei 10 месяцев назад
Родитель
Сommit
37605c9010

+ 17
- 9
websocket/src/main/java/com/xhly/websocket/service/LongConnService.java Просмотреть файл

@@ -85,6 +85,8 @@ public abstract class LongConnService extends Service {
85 85
     private WsStatus mStatus;
86 86
     private WebSocket webSocket;
87 87
     private WsListener mListener;
88
+    //是否使用单项心跳
89
+    private boolean singleheartbeat = true;
88 90
 
89 91
     /**
90 92
      * 设置已收到心跳
@@ -276,16 +278,22 @@ public abstract class LongConnService extends Service {
276 278
      * 开始socket心跳
277 279
      */
278 280
     private void startHeartInterval(final WebSocket websocket) {
279
-        if (HEART_NOT_RECEIVE_TIME > 3) {
280
-            // 有3次心跳没有收到服务器响应,则认为是已经断开连接,则重新连接
281
-            connected = false;
282
-            startConnect();
283
-            return;
281
+        if (singleheartbeat) {
282
+            //单向心跳
283
+            WebSocketHelper.getInstance().hearBeat(websocket);
284
+        } else {
285
+            //双向心跳
286
+            if (HEART_NOT_RECEIVE_TIME > 3) {
287
+                // 有3次心跳没有收到服务器响应,则认为是已经断开连接,则重新连接
288
+                connected = false;
289
+                startConnect();
290
+                return;
291
+            }
292
+            // 在客户端上增加重试的逻辑。先发送心跳包,在N秒内若没有收到回复,则再发送一次。重试M次。
293
+            WebSocketHelper.getInstance().hearBeat(websocket);
294
+            HEART_NOT_RECEIVE_TIME++;
295
+            HAS_HEART_RECEIVE = false;
284 296
         }
285
-        // 在客户端上增加重试的逻辑。先发送心跳包,在N秒内若没有收到回复,则再发送一次。重试M次。
286
-        WebSocketHelper.getInstance().hearBeat(webSocket);
287
-        HEART_NOT_RECEIVE_TIME++;
288
-        HAS_HEART_RECEIVE = false;
289 297
     }
290 298
 
291 299
     /**

+ 12
- 2
websocket/src/main/java/com/xhly/websocket/service/WebSocketHelper.java Просмотреть файл

@@ -46,10 +46,20 @@ public class WebSocketHelper {
46 46
      * @param id        心跳
47 47
      */
48 48
     public void hearBeat(WebSocket webSocket) {
49
-        HertBean hertBean = new HertBean();
49
+        /*HertBean hertBean = new HertBean();
50 50
         hertBean.setType("ping");
51 51
         String s = GsonUtils.parseClassToJson(hertBean);
52
-        send(webSocket, s);
52
+        send(webSocket, s);*/
53
+        if (webSocket == null) {
54
+            return;
55
+        }
56
+        sendExecutor.execute(new Runnable() {
57
+            @Override
58
+            public void run() {
59
+                byte[] byteArray = new byte[1];
60
+                webSocket.sendBinary(byteArray);
61
+            }
62
+        });
53 63
     }
54 64
 
55 65
     private void send(final WebSocket webSocket, final String data) {

Загрузка…
Отмена
Сохранить