【问题标题】:Stomp SockJs client + server SpringStomp SockJs 客户端 + 服务器 Spring
【发布时间】:2017-05-27 11:50:48
【问题描述】:

我有一个 Spring Boot 应用程序,我使用 npm 和 webpack。我想启动一个 websocket 将一些消息从服务器发送到客户端。我的服务器是用 java 构建的,客户端是用 stomp 和 sockjs 构建的。 这是我的代码: 客户:

    socket = new SockJS('/myWebSocketEndPoint');
    stompClient = Stomp.over(socket);
    stompClient.connect("","", function (frame) {
            console.log('Connected: ' + frame);
            stompClient.subscribe('/topic/notification', function (notificationBody) {
                  alert(angular.fromJson(notificationBody.body).content);
    });
  });
}

服务器: 配置:

    @Configuration
    @EnableWebSocketMessageBroker
    public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/myWebSocketEndPoint").withSockJS();
    }
}

控制器:

    @SendTo("/topic/notification")
    public String sendToMenuItems(String menuItem)  {
          return menuItem;
    }

问题是:当我想运行我的应用程序时,它没有使用 websocket 进行升级(似乎服务器不工作,或者客户端找不到服务器)。因此,升级请求仍处于待处理状态。如果我使用:

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/sockjs-client").withSockJS();
    }

    socket = new SockJS('/sockjs-client');

升级有效,但无法连接和订阅。为什么如果我使用第二个配置,我的应用程序(部分)可以工作,而如果我使用第一个配置却不行?非常感谢

【问题讨论】:

    标签: spring websocket npm stomp sockjs


    【解决方案1】:

    尝试替换:

    stompClient.connect("","", function (frame) {
    ...
    

    与:

    stompClient.connect({}, function (frame) {
    ...
    

    【讨论】:

      【解决方案2】:

      控制器上没有 @MessageMapping("/sockjs-client") 。 尝试将此注释与@sendUser 注释一起使用。

      【讨论】:

        【解决方案3】:

        我必须使用 setAllowedOriginPatterns 来进行此设置

        @Configuration
        @EnableWebSocketMessageBroker
        public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
        
            @Override
            public void configureMessageBroker(MessageBrokerRegistry config) {
                config.enableSimpleBroker("/topic");
                config.setApplicationDestinationPrefixes("/app");
            }
        
            @Override
            public void registerStompEndpoints(StompEndpointRegistry registry) {
                registry.addEndpoint("/live");
                registry.addEndpoint("/live").setAllowedOriginPatterns("*").withSockJS();
            }
        }
        
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-09-17
          • 2016-03-21
          • 2015-04-17
          • 2019-12-31
          • 2014-11-05
          • 2020-10-08
          • 2017-05-19
          • 2017-01-18
          相关资源
          最近更新 更多