From 91b70d5ad2ada85cf00b25f7b9ecd9cf980bf138 Mon Sep 17 00:00:00 2001
From: liusuyi <1951119284@qq.com>
Date: 星期一, 12 八月 2024 16:42:44 +0800
Subject: [PATCH] 优化:websocket接收消息

---
 ard-work/src/main/java/com/ruoyi/utils/websocket/util/WebSocketUtils.java              |   12 +++
 ard-work/src/main/java/com/ruoyi/utils/websocket/service/ChatServerEndpoint.java       |   72 ++++++++++-------------
 ard-work/src/main/java/com/ruoyi/app/position/service/impl/AppPositionPushService.java |   24 +++----
 ard-work/src/main/java/com/ruoyi/call/listener/WebsocketHandler.java                   |   68 ++++++++++++++++++++++
 4 files changed, 121 insertions(+), 55 deletions(-)

diff --git a/ard-work/src/main/java/com/ruoyi/app/position/service/impl/AppPositionPushService.java b/ard-work/src/main/java/com/ruoyi/app/position/service/impl/AppPositionPushService.java
index d60f957..a993ad1 100644
--- a/ard-work/src/main/java/com/ruoyi/app/position/service/impl/AppPositionPushService.java
+++ b/ard-work/src/main/java/com/ruoyi/app/position/service/impl/AppPositionPushService.java
@@ -88,12 +88,12 @@
             IArdAppPositionService ardAppPositionService = SpringUtils.getBean(IArdAppPositionService.class);
             ArdAppPosition ardAppPosition = ardAppPositionService.selectLastArdAppPositionByUserId(sysUser.getUserId());
             if (StringUtils.isNotNull(ardAppPosition)) {
-                Map<String, Object> params=new HashMap<>();
-                params.put("longitude",ardAppPosition.getLongitude());
-                params.put("latitude",ardAppPosition.getLatitude());
-                params.put("speed",ardAppPosition.getSpeed());
-                params.put("bearing",ardAppPosition.getBearing());
-                params.put("name",sysUser.getUserName());
+                Map<String, Object> params = new HashMap<>();
+                params.put("longitude", ardAppPosition.getLongitude());
+                params.put("latitude", ardAppPosition.getLatitude());
+                params.put("speed", ardAppPosition.getSpeed());
+                params.put("bearing", ardAppPosition.getBearing());
+                params.put("name", sysUser.getUserName());
                 ardAppPosition.setParams(params);
                 ArdAppPositions.add(ardAppPosition);
             }
@@ -108,8 +108,8 @@
             for (ArdAppPosition ardAppPosition : data) {
                 ISysUserService sysUserService = SpringUtils.getBean(ISysUserService.class);
                 SysUser sysUser = sysUserService.selectUserById(ardAppPosition.getUserId());
-                if(StringUtils.isNotNull(sysUser)) {
-                    if(StringUtils.isNotNull(sysUser.getAppOnlineState())) {
+                if (StringUtils.isNotNull(sysUser)) {
+                    if (StringUtils.isNotNull(sysUser.getAppOnlineState())) {
                         if (sysUser.getAppOnlineState().equals("1")) {
                             onlineList.add(ardAppPosition);
                         }
@@ -126,8 +126,7 @@
             Map<String, Object> map = JSONObject.parseObject(message, Map.class);
             if (map.size() > 0) {
                 Boolean enabled = (Boolean) map.get("enabled");
-                if(enabled==null)
-                {
+                if (enabled == null) {
                     return;
                 }
                 if (enabled) {
@@ -177,10 +176,9 @@
                     AppPositionPushService.tempDataMap.remove(userId);
                 }
             }
-        }
-        catch (Exception ex)
-        {
+        } catch (Exception ex) {
             log.error(ex.getMessage());
+            WebSocketUtils.sendMessage(userId, "app浣嶇疆鎺ㄩ�佽В鏋愭秷鎭��" + message + "銆戝紓甯�:" + ex.getMessage());
         }
     }
 
diff --git a/ard-work/src/main/java/com/ruoyi/call/listener/WebsocketHandler.java b/ard-work/src/main/java/com/ruoyi/call/listener/WebsocketHandler.java
new file mode 100644
index 0000000..4053708
--- /dev/null
+++ b/ard-work/src/main/java/com/ruoyi/call/listener/WebsocketHandler.java
@@ -0,0 +1,68 @@
+package com.ruoyi.call.listener;
+
+import com.alibaba.fastjson2.JSONObject;
+import com.ruoyi.call.dto.CallMessage;
+import com.ruoyi.utils.websocket.util.WebSocketUtils;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * 澶勭悊websocket娑堟伅澶勭悊瑙嗛閫氳瘽娑堟伅
+ *
+ * @author liusuyi
+ * @date 2024骞�08鏈�12鏃�15:56
+ **/
+public class WebsocketHandler {
+    public static void handleMessage(String userId, String message) {
+        try {
+            Map<String, Object> messageMap = JSONObject.parseObject(message, Map.class);
+            if (messageMap.get("type") != null && messageMap.get("type").equals("callMessage")) {
+                String msg = (String) messageMap.get("message");
+                CallMessage callMessage = JSONObject.parseObject(msg, CallMessage.class);
+                //鍗曡亰
+                if (callMessage != null && callMessage.getType().equals(0)) {
+                    WebSocketUtils.sendMessagePrefix(callMessage.getTargetId(), message);
+                }
+                //缇よ亰
+                if (callMessage != null && callMessage.getType().equals(1)) {
+                    String step = callMessage.getStep();
+                    switch (step) {
+                        case "joinRoom":
+                            Set<String> userSet = WebSocketUtils.ROOM_USER_SET.getOrDefault(callMessage.getRoomId(), new HashSet<>());
+                            userSet.add(callMessage.getUserId());
+                            WebSocketUtils.ROOM_USER_SET.put(callMessage.getRoomId(), userSet);
+                            WebSocketUtils.sendRoomMessage(callMessage.getRoomId(), message);
+                            break;
+                        case "inviteRoom":
+                            List<String> targetIds = callMessage.getTargetIds();
+                            targetIds.stream().forEach(targetId -> {
+                                WebSocketUtils.sendMessagePrefix(targetId, message);
+                            });
+                            break;
+                        case "leaveRoom":
+                            userSet = WebSocketUtils.ROOM_USER_SET.getOrDefault(callMessage.getRoomId(), new HashSet<>());
+                            if (userSet.size() > 0) {
+                                userSet.remove(callMessage.getUserId());
+                                WebSocketUtils.ROOM_USER_SET.put(callMessage.getRoomId(), userSet);
+                                WebSocketUtils.sendRoomMessage(callMessage.getRoomId(), message);
+                            }
+                            break;
+                        default:
+                            WebSocketUtils.sendMessagePrefix(callMessage.getTargetId(), message);
+                            break;
+                    }
+
+
+                }
+            }
+            else
+            {
+                WebSocketUtils.sendMessage(userId, "瑙嗛閫氳瘽鏃犳硶瑙f瀽娑堟伅銆�" + message + "銆�");
+            }
+        } catch (Exception ex) {
+            WebSocketUtils.sendMessage(userId, "瑙嗛閫氳瘽瑙f瀽娑堟伅銆�" + message + "銆戝紓甯�:" + ex.getMessage());
+        }
+    }
+}
diff --git a/ard-work/src/main/java/com/ruoyi/utils/websocket/service/ChatServerEndpoint.java b/ard-work/src/main/java/com/ruoyi/utils/websocket/service/ChatServerEndpoint.java
index ca6b465..d796d94 100644
--- a/ard-work/src/main/java/com/ruoyi/utils/websocket/service/ChatServerEndpoint.java
+++ b/ard-work/src/main/java/com/ruoyi/utils/websocket/service/ChatServerEndpoint.java
@@ -1,8 +1,12 @@
 package com.ruoyi.utils.websocket.service;
 
+import com.alibaba.fastjson2.JSON;
+import com.alibaba.fastjson2.JSONArray;
+import com.alibaba.fastjson2.JSONException;
 import com.alibaba.fastjson2.JSONObject;
 import com.ruoyi.app.position.service.impl.AppPositionPushService;
 import com.ruoyi.call.dto.CallMessage;
+import com.ruoyi.call.listener.WebsocketHandler;
 import com.ruoyi.common.exception.ServiceException;
 import com.ruoyi.utils.websocket.util.WebSocketUtils;
 import lombok.extern.slf4j.Slf4j;
@@ -44,49 +48,19 @@
     @OnMessage
     public void onMessage(@PathParam("userId") String userId, String message) {
         log.debug("鏀跺埌娑堟伅锛�" + message);
-        Map<String, Object> messageMap = JSONObject.parseObject(message, Map.class);
-        if (messageMap.get("type")!=null &&messageMap.get("type").equals("callMessage")) {
-            String msg = (String) messageMap.get("message");
-            CallMessage callMessage = JSONObject.parseObject(msg, CallMessage.class);
-            //鍗曡亰
-            if (callMessage != null && callMessage.getType().equals(0)) {
-                WebSocketUtils.sendMessagePrefix(callMessage.getTargetId(), message);
+        try {
+            if(isValidJson(message)) {
+                // 澶勭悊瑙嗛閫氳瘽娑堟伅
+                WebsocketHandler.handleMessage(userId, message);
+                // 鏍规嵁鐢ㄦ埛鏂扮殑棰戠巼閲嶆柊璋冩暣瀹氭椂浠诲姟
+                AppPositionPushService.messageHandler(userId, message);
+            } else {
+                // 澶勭悊鍏朵粬娑堟伅
+                WebSocketUtils.sendMessage(userId,"Received an invalid JSON message锛�"+message);
             }
-            //缇よ亰
-            if (callMessage != null && callMessage.getType().equals(1)) {
-                String step = callMessage.getStep();
-                switch (step) {
-                    case "joinRoom":
-                        Set<String> userSet = WebSocketUtils.ROOM_USER_SET.getOrDefault(callMessage.getRoomId(), new HashSet<>());
-                        userSet.add(callMessage.getUserId());
-                        WebSocketUtils.ROOM_USER_SET.put(callMessage.getRoomId(), userSet);
-                        WebSocketUtils.sendRoomMessage(callMessage.getRoomId(), message);
-                        break;
-                    case "inviteRoom":
-                        List<String> targetIds = callMessage.getTargetIds();
-                        targetIds.stream().forEach(targetId -> {
-                            WebSocketUtils.sendMessagePrefix(targetId, message);
-                        });
-                        break;
-                    case "leaveRoom":
-                        userSet = WebSocketUtils.ROOM_USER_SET.getOrDefault(callMessage.getRoomId(), new HashSet<>());
-                        if (userSet.size() > 0) {
-                            userSet.remove(callMessage.getUserId());
-                            WebSocketUtils.ROOM_USER_SET.put(callMessage.getRoomId(), userSet);
-                            WebSocketUtils.sendRoomMessage(callMessage.getRoomId(), message);
-                        }
-                        break;
-                    default:
-                        WebSocketUtils.sendMessagePrefix(callMessage.getTargetId(), message);
-                        break;
-                }
-
-
-            }
+        } catch (Exception ex) {
+            WebSocketUtils.sendMessage(userId, "鏃犳硶瑙f瀽娑堟伅銆�" + message + "銆�:" + ex.getMessage());
         }
-        // 鏍规嵁鐢ㄦ埛鏂扮殑棰戠巼閲嶆柊璋冩暣瀹氭椂浠诲姟
-        AppPositionPushService.messageHandler(userId, message);
-
     }
 
     @OnClose
@@ -114,4 +88,20 @@
         }
         log.info("Throwable msg " + throwable.getMessage());
     }
+
+    /**
+     * 妫�鏌ョ粰瀹氱殑瀛楃涓叉槸鍚︿负鏈夋晥鐨凧SON鏍煎紡銆�
+     *
+     * @param message 瑕佹鏌ョ殑瀛楃涓�
+     * @return 濡傛灉鏄湁鏁堢殑JSON瀛楃涓诧紝杩斿洖true锛涘惁鍒欒繑鍥瀎alse銆�
+     */
+    public static boolean isValidJson(String message) {
+        try {
+            Object json = JSON.parse(message);
+            // 纭繚瑙f瀽缁撴灉鏄疛SONObject鎴朖SONArray绫诲瀷
+            return (json instanceof JSONObject || json instanceof JSONArray);
+        } catch (JSONException e) {
+            return false;  // 瑙f瀽澶辫触锛岃鏄庝笉鏄悎娉曠殑JSON
+        }
+    }
 }
\ No newline at end of file
diff --git a/ard-work/src/main/java/com/ruoyi/utils/websocket/util/WebSocketUtils.java b/ard-work/src/main/java/com/ruoyi/utils/websocket/util/WebSocketUtils.java
index 18606e1..ab93c42 100644
--- a/ard-work/src/main/java/com/ruoyi/utils/websocket/util/WebSocketUtils.java
+++ b/ard-work/src/main/java/com/ruoyi/utils/websocket/util/WebSocketUtils.java
@@ -95,7 +95,17 @@
     public static void sendMessageAll(String message) {
         ONLINE_USER_SESSIONS.forEach((sessionId, session) -> sendMessage(session, message));
     }
-
+    /**
+     * 鍙戦�佹秷鎭粰鎸囧畾鐢ㄦ埛
+     *
+     * @param  userId 鐢ㄦ埛id
+     * @param  message 娑堟伅鍐呭
+     * @author 鍒樿嫃涔�
+     * @date   2024/8/12 15:43
+     */
+    public static void sendMessage(String userId,String message) {
+        WebSocketUtils.ONLINE_USER_SESSIONS.get(userId).getAsyncRemote().sendText(message);
+    }
     /**
      * 鎺ㄩ�佹秷鎭埌鍏朵粬瀹㈡埛绔�
      *

--
Gitblit v1.9.3