• SpringBoot整合WebSocket


    流程分析

    Websocket客户端与Websocket服务器

     前端浏览器和后端服务器的连接通信

     HTTP与Websocket对比

    前端代码

    MyComponent.vue

    1. <template>
    2. <div>
    3. <button @click="sendMessage">发送消息button>
    4. div>
    5. template>
    6. <script>
    7. export default {
    8. data() {
    9. return {
    10. socket: null,
    11. };
    12. },
    13. created() {
    14. this.connectSocket();
    15. },
    16. methods: {
    17. connectSocket() {
    18. this.socket = new WebSocket("ws://10.1.7.118:8388/bwss-facade/wsServer/1695365508391"); // 替换为你的用户ID
    19. this.socket.onopen = () => {
    20. console.log("连接成功");
    21. };
    22. this.socket.onmessage = (event) => {
    23. console.log("收到消息:", event.data);
    24. };
    25. this.socket.onerror = (error) => {
    26. console.error("WebSocket错误:", error);
    27. };
    28. },
    29. sendMessage() {
    30. if (this.socket && this.socket.readyState === WebSocket.OPEN) {
    31. this.socket.send("我是客户端,发送消息!");
    32. } else {
    33. console.error("WebSocket连接未建立");
    34. }
    35. },
    36. },
    37. };
    38. script>

     App.vue

    1. <template>
    2. <div id="app">
    3. <MyComponent />
    4. div>
    5. template>
    6. <script>
    7. import MyComponent from './components/MyComponent.vue';
    8. export default {
    9. name: 'App',
    10. components: {
    11. MyComponent
    12. }
    13. }
    14. script>

    后端编码

    1.引入pom依赖

    1. <dependency>
    2. <groupId>org.springframework.bootgroupId>
    3. <artifactId>spring-boot-starter-websocketartifactId>
    4. dependency>

    2. 编写配置类

    1. @Configuration
    2. public class WebSocketConfig
    3. {
    4. @Bean
    5. public ServerEndpointExporter serverEndpointExporter()
    6. {
    7. return new ServerEndpointExporter();
    8. }
    9. }

    3.编写服务代码

    1. import java.io.IOException;
    2. import java.util.concurrent.ConcurrentHashMap;
    3. import org.apache.commons.lang3.StringUtils;
    4. import org.springframework.stereotype.Component;
    5. import com.alibaba.fastjson.JSON;
    6. import com.alibaba.fastjson.JSONObject;
    7. import javax.websocket.*;
    8. import javax.websocket.server.PathParam;
    9. import javax.websocket.server.ServerEndpoint;
    10. /**
    11. * WebSocket服务器设置
    12. */
    13. @ServerEndpoint(value = "/wsServer/{userId}")
    14. @Component
    15. public class WebSocketServer
    16. {
    17. // concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    18. public static ConcurrentHashMap webSocketMap = new ConcurrentHashMap<>();
    19. public static ConcurrentHashMap typeMap = new ConcurrentHashMap<>();
    20. // 与某个客户端的连接会话,需要通过它来给客户端发送数据
    21. private Session session;
    22. // 接收userId
    23. private String userId = "";
    24. /**
    25. * 连接建立成功调用的方法
    26. */
    27. @OnOpen
    28. public void onOpen(Session session, @PathParam("userId") String userId)
    29. {
    30. this.session = session;
    31. this.userId = userId;
    32. if (webSocketMap.containsKey(userId))
    33. {
    34. webSocketMap.remove(userId);
    35. webSocketMap.put(userId, this);
    36. } else
    37. {
    38. webSocketMap.put(userId, this);
    39. }
    40. try
    41. {
    42. sendMessage("我是服务端,你连接成功了!");
    43. } catch (IOException e)
    44. {
    45. e.printStackTrace();
    46. }
    47. }
    48. /**
    49. * 连接关闭调用的方法
    50. */
    51. @OnClose
    52. public void onClose()
    53. {
    54. if (webSocketMap.containsKey(userId))
    55. {
    56. webSocketMap.remove(userId);
    57. }
    58. }
    59. /**
    60. * 收到客户端消息后调用的方法
    61. */
    62. @OnMessage
    63. public void onMessage(String message, Session session)
    64. {
    65. if (StringUtils.isNotBlank(message))
    66. {
    67. try
    68. {
    69. // 解析发送的报文
    70. JSONObject jsonObject = JSON.parseObject(message);
    71. String type = (String) jsonObject.get("type");
    72. if (typeMap.containsKey(type))
    73. {
    74. typeMap.remove(type);
    75. typeMap.put(type, this);
    76. } else
    77. {
    78. typeMap.put(type, this);
    79. }
    80. } catch (Exception e)
    81. {
    82. e.printStackTrace();
    83. }
    84. }
    85. }
    86. /**
    87. * 发生错误时调用
    88. */
    89. @OnError
    90. public void onError(Session session, Throwable error)
    91. {
    92. error.printStackTrace();
    93. }
    94. /**
    95. * 实现服务器主动推送
    96. */
    97. public void sendMessage(String message) throws IOException
    98. {
    99. this.session.getBasicRemote().sendText(message);
    100. }
    101. /**
    102. * 发送自定义消息
    103. */
    104. public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException
    105. {
    106. if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId))
    107. {
    108. webSocketMap.get(userId).sendMessage(message);
    109. }
    110. }
    111. }

    4.状态变更通知前端

    1. // 通过WebSocket通知前端人员下发状态变更
    2. try
    3. {
    4. // 通过map获取对应的session
    5. WebSocketServer.typeMap.get("userId").sendMessage(封装的消息体);
    6. } catch (IOException e)
    7. {
    8. throw new RuntimeException(e);
    9. }

  • 相关阅读:
    企业电子招标采购系统源码Spring Boot + Mybatis + Redis + Layui + 前后端分离 构建企业电子招采平台之立项流程图
    【MySQL】DML
    关于跨境电商货源——扬帆牧哲
    【Leetcode】剑指Offer 18:删除链表的节点
    JTAG、SWD、JLINK、ST-LINK、ULINK的区别
    河北工业大学数据挖掘实验二 数据立方体与联机分析处理构建
    微信自动化推送天气预报信息教程【Python版源代码】
    YoloV8改进策略:EfficientViT,高效的视觉transformer与级联组注意力提升YoloV8的速度和精度,打造高效的YoloV8
    【C++】类和对象(上)
    网站服务器出现404情况
  • 原文地址:https://blog.csdn.net/2301_76354366/article/details/132676433