当前位置:   article > 正文

springboot+websocket+sockjs进行消息推送_springboot websocket sockjs

springboot websocket sockjs

一,消息推送的服务端

1.创建简单的springboot工程。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. <groupId>org.springframework</groupId>
  6. <artifactId>gs-messaging-stomp-websocket</artifactId>
  7. <version>0.1.0</version>
  8. <parent>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-parent</artifactId>
  11. <version>1.4.2.RELEASE</version>
  12. </parent>
  13. <dependencies>
  14. <dependency>
  15. <groupId>org.springframework.boot</groupId>
  16. <artifactId>spring-boot-starter-web</artifactId>
  17. <exclusions>
  18. <exclusion>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-starter-tomcat</artifactId>
  21. </exclusion>
  22. </exclusions>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-jetty</artifactId>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-websocket</artifactId>
  31. <exclusions>
  32. <exclusion>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-starter-web</artifactId>
  35. </exclusion>
  36. </exclusions>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.webjars</groupId>
  40. <artifactId>webjars-locator</artifactId>
  41. </dependency>
  42. <dependency>
  43. <groupId>org.webjars</groupId>
  44. <artifactId>sockjs-client</artifactId>
  45. <version>1.0.2</version>
  46. </dependency>
  47. <dependency>
  48. <groupId>org.webjars</groupId>
  49. <artifactId>stomp-websocket</artifactId>
  50. <version>2.3.3</version>
  51. </dependency>
  52. <dependency>
  53. <groupId>org.webjars</groupId>
  54. <artifactId>bootstrap</artifactId>
  55. <version>3.3.7</version>
  56. </dependency>
  57. <dependency>
  58. <groupId>org.webjars</groupId>
  59. <artifactId>jquery</artifactId>
  60. <version>3.1.0</version>
  61. </dependency>
  62. <dependency>
  63. <groupId>org.springframework.boot</groupId>
  64. <artifactId>spring-boot-starter-actuator</artifactId>
  65. </dependency>
  66. <dependency>
  67. <groupId>org.springframework.boot</groupId>
  68. <artifactId>spring-boot-starter-test</artifactId>
  69. <scope>test</scope>
  70. </dependency>
  71. </dependencies>
  72. <properties>
  73. <java.version>1.8</java.version>
  74. </properties>
  75. <build>
  76. <plugins>
  77. <plugin>
  78. <groupId>org.springframework.boot</groupId>
  79. <artifactId>spring-boot-maven-plugin</artifactId>
  80. </plugin>
  81. </plugins>
  82. </build>
  83. </project>
去掉了默认的tomcat,采用jetty

2.采用stomp消息格式,定义接收的消息和发送的消息bean

客户端发送的消息

  1. package hello;
  2. public class Greeting {
  3. private String content;
  4. public Greeting() {
  5. }
  6. public Greeting(String content) {
  7. this.content = content;
  8. }
  9. public String getContent() {
  10. return content;
  11. }
  12. }
服务器发送给客户端的消息

  1. package hello;
  2. public class HelloMessage {
  3. private String name;
  4. public HelloMessage() {
  5. }
  6. public HelloMessage(String name) {
  7. this.name = name;
  8. }
  9. public String getName() {
  10. return name;
  11. }
  12. public void setName(String name) {
  13. this.name = name;
  14. }
  15. }
3,消息处理handler

  1. package hello;
  2. import org.springframework.messaging.handler.annotation.MessageMapping;
  3. import org.springframework.messaging.handler.annotation.SendTo;
  4. import org.springframework.stereotype.Controller;
  5. @Controller
  6. public class GreetingController {
  7. @MessageMapping("/hello")
  8. @SendTo("/topic/greetings")
  9. public Greeting greeting(HelloMessage message) throws Exception {
  10. Thread.sleep(1000); // simulated delay
  11. return new Greeting("Hello, " + message.getName() + "!");
  12. }
  13. }

4对websocket类进行配置

  1. package hello;
  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. @Configuration
  8. @EnableWebSocketMessageBroker
  9. public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
  10. @Override
  11. public void configureMessageBroker(MessageBrokerRegistry config) {
  12. config.enableSimpleBroker("/topic");
  13. config.setApplicationDestinationPrefixes("/app");
  14. }
  15. @Override
  16. public void registerStompEndpoints(StompEndpointRegistry registry) {
  17. registry.addEndpoint("/gs-guide-websocket").withSockJS();
  18. }
  19. }

创建客户端app.js和index.html

app.js文件如下:

  1. var stompClient = null;
  2. function setConnected(connected) {
  3. $("#connect").prop("disabled", connected);
  4. $("#disconnect").prop("disabled", !connected);
  5. if (connected) {
  6. $("#conversation").show();
  7. }
  8. else {
  9. $("#conversation").hide();
  10. }
  11. $("#greetings").html("");
  12. }
  13. function connect() {
  14. var socket = new SockJS('/gs-guide-websocket');
  15. stompClient = Stomp.over(socket);
  16. stompClient.connect({}, function (frame) {
  17. setConnected(true);
  18. console.log('Connected: ' + frame);
  19. stompClient.subscribe('/topic/greetings', function (greeting) {
  20. showGreeting(JSON.parse(greeting.body).content);
  21. });
  22. });
  23. }
  24. function disconnect() {
  25. if (stompClient != null) {
  26. stompClient.disconnect();
  27. }
  28. setConnected(false);
  29. console.log("Disconnected");
  30. }
  31. function sendName() {
  32. stompClient.send("/app/hello", {}, JSON.stringify({'name': $("#name").val()}));
  33. }
  34. function showGreeting(message) {
  35. $("#greetings").append("<tr><td>" + message + "</td></tr>");
  36. }
  37. $(function () {
  38. $("form").on('submit', function (e) {
  39. e.preventDefault();
  40. });
  41. $( "#connect" ).click(function() { connect(); });
  42. $( "#disconnect" ).click(function() { disconnect(); });
  43. $( "#send" ).click(function() { sendName(); });
  44. });



点解connect即与服务器建立连接,在输入框输入任何消息,点击send,发送给服务器,会获得服务器的响应,


  1. 三、服务器主动发消息给客户端服务器主动发消息给客户端通过

最后,服务器主动发消息给客户端

通过SimpleMessagingTemplate类实现

@RestController
public class TestController {

    @Autowired
    private SimpMessagingTemplate template;

    @RequestMapping(value = "/test",method = RequestMethod.GET)
    public String test(){
        template.convertAndSend("/topic/greetings",new Greeting("hello"));
        return "hello";
    }
}

调用http://localhost:8080/test,会看到消息发给了客户端


以上就是对springboot服务端进行消息推送的大致介绍。不过目前似乎消息推送系统go或nodejs版本很流行。nodejs+socketio. java服务端可以调用消息推送系统接口实现
消息发送到客户端。欢迎讨论。O(∩_∩)O~

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

闽ICP备14008679号