Pārlūkot izejas kodu

websocket添加心跳

zhifei 1 gadu atpakaļ
vecāks
revīzija
65d9cb5be0

+ 11 - 7
warewms-system/src/main/java/com/warewms/hailiang/config/DeviceMessageSocket.java

@@ -1,5 +1,6 @@
 package com.warewms.hailiang.config;
 
+import cn.hutool.json.JSONObject;
 import com.warewms.common.annotation.Anonymous;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Component;
@@ -13,13 +14,13 @@ import java.util.concurrent.CopyOnWriteArraySet;
 @Component
 @Slf4j
 @Anonymous
-@ServerEndpoint("/websocket/device/{userName}")  // 接口路径 ws://localhost:8080/device/userName;
+@ServerEndpoint("/websocket/device/{index}")  // 接口路径 ws://localhost:8080/device/userName;
 public class DeviceMessageSocket {
     //与某个客户端的连接会话,需要通过它来给客户端发送数据
     private Session session;
 
 
-    private String userName;
+    private String index;
 
 
     private static CopyOnWriteArraySet<DeviceMessageSocket> webSockets =new CopyOnWriteArraySet<>();
@@ -31,12 +32,12 @@ public class DeviceMessageSocket {
      * 链接成功调用的方法
      */
     @OnOpen
-    public void onOpen(Session session, @PathParam(value="userName")String userName) {
+    public void onOpen(Session session, @PathParam(value="index")String index) {
         try {
             this.session = session;
-            this.userName = userName;
+            this.index = index;
             webSockets.add(this);
-            sessionPool.put(userName, session);
+            sessionPool.put(index, session);
             log.info("【websocket消息】有新的连接,总数为:"+webSockets.size());
         } catch (Exception e) {
         }
@@ -49,7 +50,7 @@ public class DeviceMessageSocket {
     public void onClose() {
         try {
             webSockets.remove(this);
-            sessionPool.remove(this.userName);
+            sessionPool.remove(this.index);
         } catch (Exception e) {
         }
     }
@@ -62,6 +63,10 @@ public class DeviceMessageSocket {
     @OnMessage
     public void onMessage(String message) {
         log.info("【websocket消息】收到客户端消息:"+message);
+        JSONObject jsonObject = new JSONObject();
+        jsonObject.set("type","heartbeat");
+        jsonObject.set("content","ok");
+        sendOneMessage(message,jsonObject.toString());
     }
 
     /** 发送错误时的处理
@@ -70,7 +75,6 @@ public class DeviceMessageSocket {
      */
     @OnError
     public void onError(Session session, Throwable error) {
-
         log.error("用户错误,原因:"+error.getMessage());
         error.printStackTrace();
     }