{"id":1433,"date":"2025-06-22T06:57:42","date_gmt":"2025-06-22T06:57:42","guid":{"rendered":"https:\/\/robinluo.top\/?p=1433"},"modified":"2025-06-22T06:57:42","modified_gmt":"2025-06-22T06:57:42","slug":"ruoyi-websocket-%e5%af%b9%e6%8e%a5","status":"publish","type":"post","link":"https:\/\/robinluo.top\/?p=1433","title":{"rendered":"Ruoyi websocket \u5bf9\u63a5"},"content":{"rendered":"\n<p>\u82e5\u4f9djava\u670d\u52a1\u7aef\u6dfb\u52a0websocket \u5305<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;dependency>\r\n    &lt;groupId>org.springframework.boot&lt;\/groupId>\r\n    &lt;artifactId>spring-boot-starter-websocket&lt;\/artifactId>\r\n&lt;\/dependency><\/code><\/pre>\n\n\n\n<p>\u4e1a\u52a1\u7c7b<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.ruoyi.project.websocket;\r\n\r\nimport com.fasterxml.jackson.databind.JsonNode;\r\nimport com.fasterxml.jackson.databind.ObjectMapper;\r\nimport com.ruoyi.common.utils.StringUtils;\r\nimport com.ruoyi.framework.security.LoginUser;\r\nimport com.ruoyi.framework.security.service.TokenService;\r\nimport org.slf4j.Logger;\r\nimport org.slf4j.LoggerFactory;\r\nimport org.springframework.beans.factory.annotation.Autowired;\r\nimport org.springframework.stereotype.Component;\r\n\r\nimport javax.websocket.*;\r\nimport javax.websocket.server.ServerEndpoint;\r\nimport java.io.IOException;\r\nimport java.util.Map;\r\nimport java.util.concurrent.ConcurrentHashMap;\r\nimport java.util.concurrent.Executors;\r\nimport java.util.concurrent.ScheduledExecutorService;\r\nimport java.util.concurrent.TimeUnit;\r\nimport java.util.concurrent.atomic.AtomicInteger;\r\n\r\n@Component\r\n@ServerEndpoint(\"\/websocket\")\r\npublic class WebSocketServer {\r\n    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);\r\n    \r\n    private static final AtomicInteger onlineCount = new AtomicInteger(0);\r\n    private static final Map&lt;String, Session> sessionMap = new ConcurrentHashMap&lt;>();\r\n    private static final Map&lt;String, Long> lastActiveTimeMap = new ConcurrentHashMap&lt;>();\r\n    private static final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();\r\n    private static final long HEARTBEAT_TIMEOUT = 30000;\r\n    \r\n    private static TokenService tokenService;\r\n    \r\n    @Autowired\r\n    public void setTokenService(TokenService tokenService) {\r\n        WebSocketServer.tokenService = tokenService;\r\n    }\r\n    \r\n    private String token;\r\n    private LoginUser loginUser;\r\n    \r\n    static {\r\n        scheduler.scheduleAtFixedRate(() -> {\r\n            long currentTime = System.currentTimeMillis();\r\n            lastActiveTimeMap.forEach((token, lastActiveTime) -> {\r\n                if (currentTime - lastActiveTime > HEARTBEAT_TIMEOUT) {\r\n                    Session session = sessionMap.get(token);\r\n                    if (session != null) {\r\n                        try {\r\n                            session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, \"\u5fc3\u8df3\u8d85\u65f6\"));\r\n                        } catch (IOException e) {\r\n                            log.error(\"\u5173\u95edWebSocket\u8fde\u63a5\u5931\u8d25\", e);\r\n                        }\r\n                    }\r\n                }\r\n            });\r\n        }, 0, HEARTBEAT_TIMEOUT \/ 2, TimeUnit.MILLISECONDS);\r\n    }\r\n    \r\n    @OnOpen\r\n    public void onOpen(Session session) {\r\n        log.info(\"\u6709\u65b0\u8fde\u63a5\u52a0\u5165\uff0c\u7b49\u5f85\u8ba4\u8bc1...\");\r\n    }\r\n    \r\n    @OnClose\r\n    public void onClose() {\r\n        if (this.token != null) {\r\n            sessionMap.remove(this.token);\r\n            lastActiveTimeMap.remove(this.token);\r\n            subOnlineCount();\r\n            log.info(\"\u8fde\u63a5\u5173\u95ed\uff1a\u7528\u6237ID={}\uff0c\u5f53\u524d\u5728\u7ebf\u4eba\u6570\u4e3a\uff1a{}\", \r\n                    loginUser != null ? loginUser.getUserId() : \"unknown\", \r\n                    getOnlineCount());\r\n        }\r\n    }\r\n    \r\n    @OnMessage\r\n    public void onMessage(String message, Session session) {\r\n        try {\r\n            ObjectMapper mapper = new ObjectMapper();\r\n            JsonNode jsonNode = mapper.readTree(message);\r\n            \r\n            \/\/ \u5904\u7406\u8ba4\u8bc1\u6d88\u606f\r\n            if (this.token == null) {\r\n                if (!jsonNode.has(\"type\") || !\"AUTH\".equals(jsonNode.get(\"type\").asText())) {\r\n                    sendError(session, \"\u8bf7\u5148\u53d1\u9001\u8ba4\u8bc1\u6d88\u606f\");\r\n                    return;\r\n                }\r\n                \r\n                String token = jsonNode.get(\"token\").asText();\r\n                LoginUser user = tokenService.getLoginUser(token);\r\n                if (user == null) {\r\n                    sendError(session, \"\u65e0\u6548\u7684token\");\r\n                    session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, \"\u8ba4\u8bc1\u5931\u8d25\"));\r\n                    return;\r\n                }\r\n                \r\n                this.token = token;\r\n                this.loginUser = user;\r\n                sessionMap.put(token, session);\r\n                lastActiveTimeMap.put(token, System.currentTimeMillis());\r\n                addOnlineCount();\r\n                \r\n                log.info(\"\u8ba4\u8bc1\u6210\u529f\uff1a\u7528\u6237ID={}\uff0c\u7528\u6237\u540d={}\", user.getUserId(), user.getUsername());\r\n                \r\n                \/\/ \u53d1\u9001\u8ba4\u8bc1\u6210\u529f\u54cd\u5e94\r\n                session.getBasicRemote().sendText(mapper.writeValueAsString(Map.of(\r\n                    \"type\", \"AUTH_RESPONSE\",\r\n                    \"success\", true,\r\n                    \"message\", \"\u8ba4\u8bc1\u6210\u529f\",\r\n                    \"userId\", user.getUserId()\r\n                )));\r\n                return;\r\n            }\r\n            \r\n            \/\/ \u66f4\u65b0\u6700\u540e\u6d3b\u8dc3\u65f6\u95f4\r\n            lastActiveTimeMap.put(this.token, System.currentTimeMillis());\r\n            \r\n            \/\/ \u5904\u7406\u5fc3\u8df3\u6d88\u606f\r\n            if (jsonNode.has(\"type\") &amp;&amp; \"HEARTBEAT\".equals(jsonNode.get(\"type\").asText())) {\r\n                session.getBasicRemote().sendText(mapper.writeValueAsString(Map.of(\r\n                    \"type\", \"HEARTBEAT_ACK\"\r\n                )));\r\n                return;\r\n            }\r\n            \r\n            \/\/ \u5904\u7406\u4e1a\u52a1\u6d88\u606f\r\n            if (jsonNode.has(\"type\") &amp;&amp; \"MESSAGE\".equals(jsonNode.get(\"type\").asText())) {\r\n                String content = jsonNode.get(\"content\").asText();\r\n                log.info(\"\u6536\u5230\u6765\u81ea\u7528\u6237{}\u7684\u6d88\u606f: {}\", loginUser.getUserId(), content);\r\n                \r\n                \/\/ \u4e1a\u52a1\u5904\u7406\u903b\u8f91...\r\n                session.getBasicRemote().sendText(mapper.writeValueAsString(Map.of(\r\n                    \"type\", \"MESSAGE_RESPONSE\",\r\n                    \"content\", \"\u670d\u52a1\u5668\u6536\u5230\u6d88\u606f: \" + content,\r\n                    \"timestamp\", System.currentTimeMillis()\r\n                )));\r\n            }\r\n            \r\n        } catch (Exception e) {\r\n            log.error(\"\u5904\u7406\u6d88\u606f\u5f02\u5e38\", e);\r\n            try {\r\n                sendError(session, \"\u5904\u7406\u6d88\u606f\u65f6\u53d1\u751f\u9519\u8bef: \" + e.getMessage());\r\n            } catch (IOException ex) {\r\n                log.error(\"\u53d1\u9001\u9519\u8bef\u6d88\u606f\u5931\u8d25\", ex);\r\n            }\r\n        }\r\n    }\r\n    \r\n    @OnError\r\n    public void onError(Session session, Throwable error) {\r\n        log.error(\"WebSocket\u53d1\u751f\u9519\u8bef\", error);\r\n    }\r\n    \r\n    private void sendError(Session session, String errorMessage) throws IOException {\r\n        session.getBasicRemote().sendText(new ObjectMapper().writeValueAsString(Map.of(\r\n            \"type\", \"ERROR\",\r\n            \"message\", errorMessage\r\n        )));\r\n    }\r\n    \r\n    public static void sendToUser(String token, String message) {\r\n        Session session = sessionMap.get(token);\r\n        if (session != null &amp;&amp; session.isOpen()) {\r\n            try {\r\n                session.getBasicRemote().sendText(message);\r\n            } catch (IOException e) {\r\n                log.error(\"\u53d1\u9001\u6d88\u606f\u5931\u8d25\", e);\r\n            }\r\n        }\r\n    }\r\n    \r\n    public static void sendToUserByUserId(Long userId, String message) {\r\n        sessionMap.forEach((token, session) -> {\r\n            try {\r\n                LoginUser user = tokenService.getLoginUser(token);\r\n                if (user != null &amp;&amp; userId.equals(user.getUserId())) {\r\n                    session.getBasicRemote().sendText(message);\r\n                }\r\n            } catch (Exception e) {\r\n                log.error(\"\u901a\u8fc7\u7528\u6237ID\u53d1\u9001\u6d88\u606f\u5f02\u5e38\", e);\r\n            }\r\n        });\r\n    }\r\n    \r\n    public static int getOnlineCount() {\r\n        return onlineCount.get();\r\n    }\r\n    \r\n    public static void addOnlineCount() {\r\n        onlineCount.incrementAndGet();\r\n    }\r\n    \r\n    public static void subOnlineCount() {\r\n        onlineCount.decrementAndGet();\r\n    }\r\n}<\/code><\/pre>\n\n\n\n<p>\u524d\u7aef\u6dfb\u52a0websocket\u64cd\u4f5c\u7c7b \u4e14\u4f5c\u4e3a\u5168\u5c40\u5355\u4f8b\u6a21\u5f0f \u4efb\u4f55\u6587\u4ef6\u90fd\u53ef\u4ee5\u8c03\u7528<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { getToken } from '@\/utils\/auth'\r\nimport { Message, MessageBox } from 'element-ui'\r\n\r\nclass WebSocketClient {\r\n  constructor(options = {}) {\r\n    const defaultOptions = {\r\n      url: '',\r\n      heartBeat: 30000,          \/\/ \u5fc3\u8df3\u95f4\u969430\u79d2\r\n      reconnectDelay: 5000,       \/\/ \u91cd\u8fde\u5ef6\u8fdf5\u79d2\r\n      maxReconnectAttempts: 5,    \/\/ \u6700\u5927\u91cd\u8fde\u6b21\u6570\r\n      onOpen: () => {},\r\n      onMessage: () => {},\r\n      onClose: () => {},\r\n      onError: () => {},\r\n      onAuthenticated: () => {}   \/\/ \u65b0\u589e\u8ba4\u8bc1\u6210\u529f\u56de\u8c03\r\n    }\r\n\r\n    this.options = { ...defaultOptions, ...options }\r\n    this.ws = null\r\n    this.reconnectAttempts = 0\r\n    this.heartBeatTimer = null\r\n    this.isManualClose = false\r\n    this.isAuthenticated = false  \/\/ \u8ba4\u8bc1\u72b6\u6001\r\n  }\r\n\r\n  connect() {\r\n    if (this.ws) {\r\n      this.close()\r\n    }\r\n\r\n    this.ws = new WebSocket(this.options.url)\r\n\r\n    this.ws.onopen = (event) => {\r\n      this.reconnectAttempts = 0\r\n      this.options.onOpen(event)\r\n      \r\n      \/\/ \u8fde\u63a5\u5efa\u7acb\u540e\u7acb\u5373\u53d1\u9001\u8ba4\u8bc1\u6d88\u606f\r\n      this.sendAuthMessage()\r\n      \r\n      this.startHeartBeat()\r\n    }\r\n\r\n    this.ws.onmessage = (event) => {\r\n      try {\r\n        const data = JSON.parse(event.data)\r\n        \r\n        \/\/ \u5904\u7406\u8ba4\u8bc1\u54cd\u5e94\r\n        if (data.type === 'AUTH_RESPONSE') {\r\n          if (data.success) {\r\n            this.isAuthenticated = true\r\n            this.options.onAuthenticated(data)\r\n            Message.success('WebSocket\u8ba4\u8bc1\u6210\u529f')\r\n          } else {\r\n            Message.error(data.message || 'WebSocket\u8ba4\u8bc1\u5931\u8d25')\r\n            this.close()\r\n          }\r\n          return\r\n        }\r\n        \r\n        \/\/ \u5176\u4ed6\u6d88\u606f\u5904\u7406\r\n        this.options.onMessage(event)\r\n        this.resetHeartBeat()\r\n      } catch (e) {\r\n        console.error('\u6d88\u606f\u89e3\u6790\u5931\u8d25:', e)\r\n      }\r\n    }\r\n\r\n    this.ws.onclose = (event) => {\r\n      this.isAuthenticated = false\r\n      this.options.onClose(event)\r\n      this.stopHeartBeat()\r\n      \r\n      if (!this.isManualClose) {\r\n        this.reconnect()\r\n      }\r\n    }\r\n\r\n    this.ws.onerror = (error) => {\r\n      this.options.onError(error)\r\n      this.stopHeartBeat()\r\n      \r\n      if (!this.isManualClose) {\r\n        this.reconnect()\r\n      }\r\n    }\r\n  }\r\n\r\n  \/\/ \u53d1\u9001\u8ba4\u8bc1\u6d88\u606f\r\n  sendAuthMessage() {\r\n    const token = getToken()\r\n    if (!token) {\r\n      Message.error('\u672a\u83b7\u53d6\u5230\u767b\u5f55Token\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55')\r\n      this.close()\r\n      return\r\n    }\r\n\r\n    this.send({\r\n      type: 'AUTH',\r\n      token: token,\r\n      timestamp: new Date().getTime()\r\n    })\r\n  }\r\n\r\n  send(data) {\r\n    if (this.ws &amp;&amp; this.ws.readyState === WebSocket.OPEN) {\r\n      this.ws.send(JSON.stringify(data))\r\n    } else {\r\n      console.error('WebSocket\u672a\u8fde\u63a5')\r\n    }\r\n  }\r\n\r\n  \/\/ \u5176\u4ed6\u65b9\u6cd5\u4fdd\u6301\u4e0d\u53d8...\r\n  close() { \/* ... *\/ }\r\n  reconnect() { \/* ... *\/ }\r\n  startHeartBeat() { \/* ... *\/ }\r\n  stopHeartBeat() { \/* ... *\/ }\r\n  resetHeartBeat() { \/* ... *\/ }\r\n}\r\n\r\n\/\/ \u5168\u5c40\u5355\u4f8b\r\nlet wsInstance = null\r\n\r\nexport function initWebSocket() {\r\n  if (wsInstance) {\r\n    return wsInstance\r\n  }\r\n\r\n  wsInstance = new WebSocketClient({\r\n    url: process.env.VUE_APP_WS_API,\r\n    onAuthenticated: (data) => {\r\n      \/\/ \u8ba4\u8bc1\u6210\u529f\u540e\u7684\u5904\u7406\r\n      console.log('WebSocket\u8ba4\u8bc1\u6210\u529f', data)\r\n    },\r\n    onMessage: (event) => {\r\n      try {\r\n        const data = JSON.parse(event.data)\r\n        if (data.type === 'NOTIFICATION') {\r\n          MessageBox.alert(data.content, data.title || '\u7cfb\u7edf\u901a\u77e5', {\r\n            confirmButtonText: '\u786e\u5b9a',\r\n            type: data.level || 'info'\r\n          })\r\n        }\r\n      } catch (e) {\r\n        console.error('\u6d88\u606f\u5904\u7406\u9519\u8bef:', e)\r\n      }\r\n    },\r\n    onError: (error) => {\r\n      Message.error('WebSocket\u8fde\u63a5\u9519\u8bef: ' + error.message)\r\n    }\r\n  })\r\n\r\n  return wsInstance\r\n}\r\n\r\nexport function getWebSocket() {\r\n  return wsInstance\r\n}\r\n\r\nexport function closeWebSocket() {\r\n  if (wsInstance) {\r\n    wsInstance.close()\r\n    wsInstance = null\r\n  }\r\n}<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u82e5\u4f9djava\u670d\u52a1\u7aef\u6dfb\u52a0websocket \u5305 \u4e1a\u52a1\u7c7b \u524d\u7aef\u6dfb\u52a0websocket\u64cd\u4f5c\u7c7b \u4e14\u4f5c\u4e3a\u5168\u5c40\u5355\u4f8b\u6a21\u5f0f \u4efb\u4f55\u6587\u4ef6\u90fd\u53ef\u4ee5\u8c03\u7528<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[8],"tags":[206,223],"_links":{"self":[{"href":"https:\/\/robinluo.top\/index.php?rest_route=\/wp\/v2\/posts\/1433"}],"collection":[{"href":"https:\/\/robinluo.top\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/robinluo.top\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/robinluo.top\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/robinluo.top\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1433"}],"version-history":[{"count":2,"href":"https:\/\/robinluo.top\/index.php?rest_route=\/wp\/v2\/posts\/1433\/revisions"}],"predecessor-version":[{"id":1435,"href":"https:\/\/robinluo.top\/index.php?rest_route=\/wp\/v2\/posts\/1433\/revisions\/1435"}],"wp:attachment":[{"href":"https:\/\/robinluo.top\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1433"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/robinluo.top\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1433"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/robinluo.top\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1433"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}