当前位置:   article > 正文

springboot+sockjs进行消息推送(群发)_springboot sockjs

springboot sockjs

 

首先是pom

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.1.5.RELEASE</version>
  9. <relativePath /> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.baidu.websocket</groupId>
  12. <artifactId>websocket</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>websocket</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-websocket</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-test</artifactId>
  27. <scope>test</scope>
  28. </dependency>
  29. <dependency>
  30. <groupId>ch.qos.logback</groupId>
  31. <artifactId>logback-classic</artifactId>
  32. <version>1.2.3</version>
  33. </dependency>
  34. <dependency>
  35. <groupId>ch.qos.logback</groupId>
  36. <artifactId>logback-core</artifactId>
  37. <version>RELEASE</version>
  38. </dependency>
  39. <!-- 进行页面跳转 -->
  40. <dependency>
  41. <groupId>org.springframework.boot</groupId>
  42. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  43. </dependency>
  44. <dependency>
  45. <groupId>org.webjars</groupId>
  46. <artifactId>jquery</artifactId>
  47. <version>3.1.0</version>
  48. </dependency>
  49. <!-- 热部署 -->
  50. <!-- devtools可以实现页面热部署(即页面修改后会立即生效,
  51. 这个可以直接在application.properties文件中配置spring.thymeleaf.cache=false来实现) -->
  52. <!-- 实现类文件热部署(类文件修改后不会立即生效),实现对属性文件的热部署。 -->
  53. <!-- 即devtools会监听classpath下的文件变动,并且会立即重启应用(发生在保存时机),
  54. 注意:因为其采用的虚拟机机制,该项重启是很快的 -->
  55. <!-- (1)base classloader (Base类加载器):加载不改变的Class,例如:第三方提供的jar包。 -->
  56. <!-- (2)restart classloader(Restart类加载器):加载正在开发的Class。 -->
  57. <!-- 为什么重启很快,因为重启的时候只是加载了在开发的Class,没有重新加载第三方的jar包。 -->
  58. <dependency>
  59. <groupId>org.springframework.boot</groupId>
  60. <artifactId>spring-boot-devtools</artifactId>
  61. <!-- optional=true, 依赖不会传递, 该项目依赖devtools;
  62. 之后依赖boot项目的项目如果想要使用devtools, 需要重新引入 -->
  63. <optional>true</optional>
  64. </dependency>
  65. </dependencies>
  66. <build>
  67. <plugins>
  68. <plugin>
  69. <groupId>org.springframework.boot</groupId>
  70. <artifactId>spring-boot-maven-plugin</artifactId>
  71. </plugin>
  72. </plugins>
  73. </build>
  74. </project>

 接下来是配置文件sockjs的配置文件

  1. package com.baidu.websocket.config;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.messaging.simp.config.MessageBrokerRegistry;
  4. import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
  5. import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
  6. import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
  7. /**
  8. * 配置WebSocket
  9. */
  10. @Configuration
  11. //注解开启使用STOMP协议来传输基于代理(message broker)的消息,这时控制器支持使用@MessageMapping,就像使用@RequestMapping一样
  12. @EnableWebSocketMessageBroker
  13. public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{
  14. @Override
  15. //注册STOMP协议的节点(endpoint),并映射指定的url
  16. public void registerStompEndpoints(StompEndpointRegistry registry) {
  17. //注册一个STOMP的endpoint,并指定使用SockJS协议
  18. registry.addEndpoint("/endpointOyzc").setAllowedOrigins("*").withSockJS();
  19. }
  20. @Override
  21. //配置消息代理(Message Broker)
  22. public void configureMessageBroker(MessageBrokerRegistry registry) {
  23. //点对点应配置一个/user消息代理,广播式应配置一个/topic消息代理,群发(mass),单独聊天(alone)
  24. registry.enableSimpleBroker("/topic","/user","/mass","/alone");
  25. //点对点使用的订阅前缀(客户端订阅路径上会体现出来),不设置的话,默认也是/user/
  26. registry.setUserDestinationPrefix("/user");
  27. }
  28. }

 接下来是Controller

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.messaging.handler.annotation.MessageMapping;
  3. import org.springframework.messaging.handler.annotation.SendTo;
  4. import org.springframework.messaging.simp.SimpMessagingTemplate;
  5. import org.springframework.stereotype.Controller;
  6. import com.baidu.websocket.model.ChatRoomRequest;
  7. import com.baidu.websocket.model.ChatRoomResponse;
  8. @Controller
  9. public class qunfacontroller {
  10. @Autowired
  11. private SimpMessagingTemplate template;
  12. //websocket前端向后端发送的地址
  13. @MessageMapping("/qunfamassage")
  14. //websocket后端向前端发送的地址
  15. @SendTo("/topic/getResponse")
  16. public ChatRoomResponse mass(ChatRoomRequest chatRoomRequest){
  17. //方法用于群发测试
  18. System.out.println("姓名是 = " + chatRoomRequest.getName());
  19. System.out.println("消息是 = " + chatRoomRequest.getChatValue());
  20. ChatRoomResponse response=new ChatRoomResponse();
  21. response.setName(chatRoomRequest.getName());
  22. response.setChatValue(chatRoomRequest.getChatValue());
  23. return response;
  24. }
  25. }

 接下来是ChatRoomResponse类

  1. public class ChatRoomResponse {
  2. private String userId;
  3. private String name;
  4. private String chatValue;
  5. public String getUserId() {
  6. return userId;
  7. }
  8. public void setUserId(String userId) {
  9. this.userId = userId;
  10. }
  11. public String getName() {
  12. return name;
  13. }
  14. public void setName(String name) {
  15. this.name = name;
  16. }
  17. public String getChatValue() {
  18. return chatValue;
  19. }
  20. public void setChatValue(String chatValue) {
  21. this.chatValue = chatValue;
  22. }
  23. }

接下来是ChatRoomRequest类

  1. public class ChatRoomRequest {
  2. private String userId;
  3. private String name;
  4. private String chatValue;
  5. public String getUserId() {
  6. return userId;
  7. }
  8. public void setUserId(String userId) {
  9. this.userId = userId;
  10. }
  11. public String getName() {
  12. return name;
  13. }
  14. public void setName(String name) {
  15. this.name = name;
  16. }
  17. public String getChatValue() {
  18. return chatValue;
  19. }
  20. public void setChatValue(String chatValue) {
  21. this.chatValue = chatValue;
  22. }
  23. }

接下来写前端

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>这是一个群发的Message</title>
  6. <style type="text/css">
  7. * {
  8. margin: 0;
  9. padding: 0;
  10. }
  11. #top {
  12. text-align: center;
  13. margin-top: 10px;
  14. }
  15. #left {
  16. width: 700px;
  17. height: 600px;
  18. float: left;
  19. background: #dddddd;
  20. border: 1px solid #a1a1a1;;
  21. border-radius: 25px;
  22. margin-left: 30px;
  23. margin-top: 30px;
  24. }
  25. #right {
  26. width: 700px;
  27. height: 600px;
  28. float: right;
  29. background: #dddddd;
  30. border: 1px solid #a1a1a1;;
  31. border-radius: 25px;
  32. margin-right: 30px;
  33. margin-top: 30px;
  34. }
  35. #selectuser {
  36. text-align: center;
  37. margin-top: 10px;
  38. }
  39. #sendChatValue {
  40. width: 90%;
  41. height: 400px;
  42. margin-top: 20px;
  43. margin-right: 20px;
  44. margin-left: 20px;
  45. margin-bottom: 20px;
  46. }
  47. #input {
  48. text-align: center;
  49. }
  50. #message {
  51. margin-top: 20px;
  52. margin-left: 20px;
  53. }
  54. input {
  55. font-size: 15px;
  56. height: 30px;
  57. width: 50px;
  58. border-radius: 4px;
  59. border: 2px solid #c8cccf;
  60. color: #6a6f77;
  61. }
  62. select {
  63. font-size: 15px;
  64. height: 30px;
  65. border-radius: 4px;
  66. border: 2px solid #c8cccf;
  67. color: #6a6f77;
  68. }
  69. </style>
  70. </head>
  71. <body>
  72. <!-- 头部 -->
  73. <div id="top">
  74. <h1>这是一个群发的Message</h1>
  75. </div>
  76. <div id="left">
  77. <div id="selectuser">
  78. <select id="selectName">
  79. <option value="1">请选择发送用户</option>
  80. <option value="张三">张三</option>
  81. <option value="李四">李四</option>
  82. <option value="王五">王五</option>
  83. <option value="小六">小六</option>
  84. </select>
  85. </div>
  86. <div>
  87. <textarea name="sendChatValue" id="sendChatValue"
  88. class="sendChatValue"></textarea>
  89. <div id="input">
  90. <input type="button" name="sendMessage" id="sendMessage"
  91. class="btn btn-default" onclick="sendMassMessage()" value="发送">
  92. </div>
  93. </div>
  94. </div>
  95. <div id="right">
  96. <div id="message"></div>
  97. </div>
  98. <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.slim.js"></script>
  99. <script type="text/javascript" src="js/qunfa.js" charset="utf-8"></script>
  100. <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
  101. <script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
  102. </body>
  103. </html>

 接下来写qunfa.js

  1. var stompClient = null;
  2. //加载完浏览器后 调用connect(),打开双通道
  3. $(function(){
  4. //打开双通道
  5. connect()
  6. })
  7. //强制关闭浏览器 调用websocket.close(),进行正常关闭
  8. window.onunload = function() {
  9. disconnect()
  10. }
  11. //打开双通道
  12. function connect(){
  13. var socket = new SockJS('/endpointOyzc'); //连接SockJS的endpoint名称为"endpointAric"
  14. stompClient = Stomp.over(socket);//使用STMOP子协议的WebSocket客户端
  15. stompClient.connect({},function(frame){//连接WebSocket服务端
  16. console.log('Connected:' + frame);
  17. //广播接收信息
  18. console.log('开始接受消息...');
  19. stompTopic();
  20. console.log('消息接受完毕');
  21. });
  22. }
  23. //关闭双通道
  24. function disconnect(){
  25. if(stompClient != null) {
  26. stompClient.disconnect();
  27. }
  28. console.log("Disconnected");
  29. }
  30. //广播(一对多)
  31. function stompTopic(){
  32. console.log('进入广播接受模式...');
  33. //通过stompClient.subscribe订阅/topic/getResponse 目标(destination)发送的消息(广播接收信息)
  34. stompClient.subscribe('/topic/getResponse',function(response){
  35. var message=JSON.parse(response.body);
  36. //展示广播的接收的内容接收
  37. var response = $("#message");
  38. response.append("<p>发消息的人是:<span style='color:#F00'>"+message.name+"&nbsp &nbsp</span>发送的信息是:<span style='color:#F00'>"+message.chatValue+"</span></p>");
  39. });
  40. }
  41. //群发消息
  42. function sendMassMessage(){
  43. var postValue={};
  44. var chatValue=$("#sendChatValue");
  45. var userName=$("#selectName").val();
  46. postValue.name=userName;
  47. postValue.chatValue=chatValue.val();
  48. if(userName==1||userName==null){
  49. alert("请选择你是谁!");
  50. return;
  51. }
  52. if(chatValue==""||userName==null){
  53. alert("不能发送空消息!");
  54. return;
  55. }
  56. stompClient.send("/qunfamassage",{},JSON.stringify(postValue));
  57. chatValue.val("");
  58. console.log('消息已发出');
  59. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/178669
推荐阅读
相关标签