Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaSpringBootWebSocket与JS的通信_Java_Spring_Spring Boot_Websocket_Stomp - Fatal编程技术网

JavaSpringBootWebSocket与JS的通信

JavaSpringBootWebSocket与JS的通信,java,spring,spring-boot,websocket,stomp,Java,Spring,Spring Boot,Websocket,Stomp,我的Spring boot应用程序中有以下WebSocketConfig: @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) {

我的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");
    }
@Controller
public class SomeController {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    @Scheduled(fixedDelay = 1000)
    private void send() {
        simpMessagingTemplate.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,但我无法收到任何消息

控制台日志显示所有问题:

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


你知道哪里出了问题吗?

对不起,我没有足够的声誉在你的帖子上留言,所以我会回复

  • 您可以启用登录
    application.properties
    ,查看WS-connection的实际情况

    logging.level.org.springframework.messaging=trace
    logging.level.org.springframework.web.socket=trace
    
  • 未定义连接到服务器
    并不意味着有问题。这一行每次都出现

  • 我试着复制你的问题,在我这方面效果很好。您是否有额外的路由或安全配置(我注意到https和自定义端口)?以下是您需要检查的代码:

  • 控制器:

    @Autowired
        private SimpMessagingTemplate template;
    
        @Scheduled(fixedRate = 5000)
        public void getMessage() {
            System.out.println("scheduled");
            this.template.convertAndSend("/topic/updateService", "Hello");
        }
    
    @Controller
    public class SomeController {
    
        @Autowired
        private SimpMessagingTemplate simpMessagingTemplate;
    
        @Scheduled(fixedDelay = 1000)
        private void send() {
            simpMessagingTemplate.convertAndSend("/topic/updateService", "Hello");
        }
    }
    
    主应用程序和Websocket配置(不要忘记
    @EnableWebSocketMessageBroker
    ):

    这是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>
    
    
    var stompClient=null;
    函数连接(){
    var socket=new SockJS(“http://localhost:8443/ws");
    stompClient=Stomp.over(套接字);
    stompClient.connect({},函数(){
    stompClient.subscribe('/topic/updateService',函数(数据){
    控制台日志(数据);
    });
    });
    }
    功能断开(){
    if(stompClient!=null){
    stompClient.disconnect();
    }
    控制台日志(“断开”);
    }
    
    我知道这个问题很老,但也许我的回答会帮助其他人

    我也有类似的问题。我的任务是让用户不断更新一些正在进行的过程,所以我的应用程序必须每5秒发送一条消息

    前端Vue.js应用程序在节点上单独提供服务。必须监视我添加的任务的内部组件:

    <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>
    
    正如您可能看到的,我不重写
    configureMessageBroker
    方法

    在主类中,我启用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
    时,我必须将完整目的地作为参数写入

    如果您看到
    stomp.min.js
    它在
    log
    中说
    连接到未定义的服务器
    !这不是一个错误吗!如果您连接到
    未定义的服务器
    那么您应该如何获取消息我认为这与此无关,但连接到未定义的服务器是不可能的,当我在代码中更改主机时,我收到一个错误,因为这更像是一个注释,这里的解决方案是什么?在我的情况下,原来我的控制器正在发送到
    /topic/updateService
    ,但我的代理已注册到
    /topic
    ,我的客户正在收听
    /topic/updateService
    (注意前面的反斜杠)。一旦我在控制器目的地前面加上反斜杠(即将
    @SendTo(“topic/updateService”)
    更改为
    @SendTo(“/topic/updateService”)
    ),消息就会通过。简言之,我必须确保我的路径匹配。