一、后端springboot代码
1、 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2 、websocket配置
@Slf4j
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
// 客户端订阅消息的前缀:topic用来广播,user用来实现点对点
registry.enableSimpleBroker("/topic", "/user");
// 点对点发送前缀
registry.setUserDestinationPrefix("/user");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// 注册STOMP的endpoint,前端建立socket连接时url(http://127.0.0.1:8080/api)
registry.addEndpoint("/api").setAllowedOrigins("*").withSockJS();
}
}
3、发送消息(http方式发送消息)
@RestController
@RequestMapping("/socket")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WebsocketController {
private final SimpMessagingTemplate simpMessagingTemplate;
@PostMapping("/sendMsg")
public Result<String> sendMsg(){
simpMessagingTemplate.convertAndSend("/topic/all","今天10点开项目启动会-所有人");
return Result.SUCCESS();
}
@PostMapping("/sendOne")
public Result<String> sendOne(){
simpMessagingTemplate.convertAndSendToUser("111111","/queue/cmdFinish","今天10点开项目启动会-linxin");
return Result.SUCCESS();
}
}
二、 前端vue代码
1、安装npm依赖包
npm install sockjs-client --save
npm install stompjs --save
2、订阅后端推送的消息(发送消息暂时就用http方式调用后端接口)
<script>
import SockJS from 'sockjs-client/dist/sockjs.min.js';
import Stomp from 'stompjs';
export default {
data: function() {
return{
stompClient:null,
sockjs:null
}
},
mounted(){
this.initWebSocket();
},
beforeDestroy() {
// 页面离开时断开连接
this.disconnect()
},
methods:{
initWebSocket:function(){
let that = this;
// 建立连接对象
that.socket = new SockJS("http://127.0.0.1L8080/api");
// 获取STOMP子协议的客户端对象
that.stompClient = Stomp.over(that.socket);
that.stompClient.debug = false
that.stompClient.reconnect_delay = 5000
// 建立连接
that.stompClient.connect({},(frame)=>{
// 订阅主题
that.stompClient.subscribe('/topic/all',res=>{
console.info('res',res);
that.$message({
message:res.body,
type:'success',
duration:3000
});
});
// 订阅点对点消息 username=111111(对应后端代码 simpMessagingTemplate.convertAndSendToUser("111111","/queue/cmdFinish","今天10点开项目启动会-linxin");)
that.stompClient.subscribe(`/user/${that.username}/queue/cmdFinish`,res=>{
console.info('res',res);
that.$message({
message:res.body,
type:'success',
duration:3000
});
});
});
},
disconnect:function(){
if (this.stompClient) {
this.stompClient.disconnect()
}
}
}
};
</script>
3、退出登录时调用disconnect方法断开连接