代码之家  ›  专栏  ›  技术社区  ›  TheUnreal

Java Spring boot websocket与JS的通信

  •  4
  • TheUnreal  · 技术社区  · 7 年前

    我的Spring boot应用程序中有以下WebSocketConfig:

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

    我的控制器中的代码:

    @Autowired
        private SimpMessagingTemplate template;
    
        @Scheduled(fixedRate = 5000)
        public void getMessage() {
            System.out.println("scheduled");
            this.template.convertAndSend("/topic/updateService", "Hello");
        }
    

    我试图用我的javascript应用程序以这种方式读取这些消息:

    let socket = new SockJS(`https://localhost:8443/ws`);
        let stompClient = Stomp.over(socket);
    
        stompClient.connect({}, () => {
          stompClient.subscribe('/topic/updateService', (data) => {
            console.log("New message!");
            console.log(data);
          });
        }, () => {
          console.log('failed');
        });
    

    虽然我订阅了/updateService,但我没有收到任何消息。

    控制台日志显示一切正常:

    enter image description here

    虽然在我的Spring boot应用程序中我看到了 scheduled 在我的控制台中,我的客户端没有收到任何消息。

    你知道哪里出了问题吗?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Dmitry Zlykh    7 年前

    1. 您可以启用登录 application.properties 了解WS-connection的实际情况。

      logging.level.org.springframework.messaging=trace
      logging.level.org.springframework.web.socket=trace
      
    2. connected to server undefined

    3. 我试着复制你的问题,对我来说效果很好。你有额外的路由或安全配置吗(我注意到http s 和自定义端口)?以下是您需要检查的代码:

    @Controller
    public class SomeController {
    
        @Autowired
        private SimpMessagingTemplate simpMessagingTemplate;
    
        @Scheduled(fixedDelay = 1000)
        private void send() {
            simpMessagingTemplate.convertAndSend("/topic/updateService", "Hello");
        }
    }
    

    主应用程序(&M);Websocket配置(不要忘记 @EnableWebSocketMessageBroker ):

    @SpringBootApplication
    @EnableScheduling
    @EnableWebSocketMessageBroker
    public class Main extends AbstractWebSocketMessageBrokerConfigurer {
        public static void main(String[] args) {
            SpringApplication.run(Main.class, args);
        }
    
        @Override
        public void registerStompEndpoints(StompEndpointRegistry registry) {
            registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();
        }
    
        @Override
        public void configureMessageBroker(MessageBrokerRegistry registry) {
            registry.setApplicationDestinationPrefixes("/app");
            registry.enableSimpleBroker("/topic");
        }
    }
    

    这是JS代码:

    <script type="text/javascript">
            var stompClient = null;
    
            function connect() {
                var socket = new SockJS("http://localhost:8443/ws");
                stompClient = Stomp.over(socket);
                stompClient.connect({}, function () {
                    stompClient.subscribe('/topic/updateService', function (data) {
                        console.log(data);
                    });
                });
            }
    
            function disconnect() {
                if (stompClient != null) {
                    stompClient.disconnect();
                }
                console.log("Disconnected");
            }
    
    </script>
    
        2
  •  0
  •   FirePapaya    5 年前

    我知道这个问题很老,但也许我的回答会帮助别人。

    <script>    
    import SockJS from 'sockjs-client'
    const Stomp = require('stompjs')
    const socket = new SockJS('http://localhost:8088/monitor/activity',{transports: ['websocket'] })
    
    // Usual Vue-js stuff
    methods: {
      subscribe (frame) {
        console.log('Subscribed to: ' + frame)
        this.stompClient.subscribe('/web-socket/activity', (payload) => {
          console.log('Successfully handled message :' + payload)
        })
      },
      connect () {
        this.stompClient = Stomp.over(socket)
        this.stompClient.connect({}, this.subscribe)
      }
    },
    mounted() {
      this.connect
    }
    </script>
    

    在服务器端(用Kotlin编写的Spring应用程序),我添加了配置类

    @Configuration
    class WebSocketConfig : WebSocketMessageBrokerConfigurer {
    
        override fun registerStompEndpoints(registry: StompEndpointRegistry) {
    
            registry.addEndpoint("/monitor/activity")
                    .setAllowedOrigins("*")
                    .withSockJS()
        }
    }
    

    如你所见,我 不要 推翻 configureMessageBroker 方法

    在主类I中,启用web套接字和调度

    @SpringBootApplication
    @EnableScheduling
    @EnableWebSocketMessageBroker
    @EnableWebSocket
    public class SpringBootVuejsApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringBootVuejsApplication.class, args);
        }
    }
    

    下面是向套接字发送消息的组件:

    @Component
    class LoanScheduledCron
    @Autowired constructor(
            private val messagingTemplate: SimpMessagingTemplate
    ) {
    
        @Scheduled(fixedDelay = 5000)
        fun getSchedulersActivity () {
            messagingTemplate.convertAndSend("/web-socket/activity", "Still active")
        }
    }
    

    请注意,在调用方法时,我必须将完整目的地作为参数写入 convertAndSend .