1.问题困扰我好几天了。我用vue做前后分离去连接Springboot后台
//这是SpringBoot后台
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer{
@Autowired
private SimpMessagingTemplate template;
//广播推送消息
@Scheduled(fixedRate = 10000)
public void sendTopicMessage() {
System.out.println("后台广播推送!");
User user=new User();
user.setUserName("oyzc");
user.setAge(10);
this.template.convertAndSend("/topic/getResponse",user);
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/endpoint-websocket").setAllowedOrigins("*").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic","/chat");
registry.setApplicationDestinationPrefixes("/app");
}
}
用的是Springboot整合的websocket
//这是vue,JS页面
<template>
<div >
</div>
</template>
<script>
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
export default {
data(){
return {
stompClient:'',
timer:'',
msg:'SocketJS'
}
},
methods:{
connection(){
let socket = new SockJS('http://localhost:8080/endpoint-websocket');
debugger;
this.stompClient = Stomp.over(socket);
console.log('stompClient:' + this.stompClient);
this.stompClient.connect({}, function(frame){
console.log('Connected:' + frame);
this.stompClient.subscribe('/topic/getResponse', (result) => {
console.info(result)
showContent(Json.parse(result.body));
});
});
},
disconnect() {
if (this.stompClient) {
this.stompClient.disconnect();
}
}, // 断开连接
},
mounted(){
this.connection();
},
beforeDestroy: function () {
// 页面离开时断开连接,清除定时器
this.disconnect();
}
}
</script>
<style scoped>
</style>
以下是浏览器报错信息