网上有很多方法,这里写一下我使用到的方法。
官方文档:
https://docs.spring.io/spring/docs/5.2.5.RELEASE/spring-framework-reference/web.html#websocket
环境
1)在build.gradle添加引用compile("org.springframework.boot:spring-boot-starter-websocket")
2)还要有2个JS文件:sockjs.min.js
和stomp.min.js
配置
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic", "/queue");
registry.setApplicationDestinationPrefixes("/app");
registry.setUserDestinationPrefix("/user/");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/myEndPoint").setAllowedOrigins().withSockJS();
}
}
js文件
if('WebSocket' in window){
var socket = new SockJS('/myEndPoint');
websocket = Stomp.over(socket);
websocket.connect({},function(frame){
send();
websocket.subscribe('/topic/newMsg',function(response){
var responseData = JSON.parse(response.body);
// do your sth.
});
},function(err){
console.log(err);
});
}
function send(){
websocket.send("/app/msg",{}, "");
}
websocket.onopen = function (e) {
console.log(e);
};
websocket.onmessage = function (e) {
console.log(e)
};
websocket.onerror = function (e) {
console.log(e);
};
websocket.onclose = function (e) {
console.log(e);
}
接收端
@MessageMapping("/msg")
public void msg() {
// do your sth.
}
发送端
@Autowired
private SimpMessagingTemplate messagingTemplate;
//.....
messagingTemplate.convertAndSend("/topic/newMsg", obj);
上面这些配置是所有人都收到,如果只想发给某个人呢?
https://stackoverflow.com/questions/22367223/sending-message-to-specific-user-on-spring-websocket
发给某个人的配置
【如果要发给个人,一定是配置了Security,这样才有用户的概念】
JS(要注意url加了前缀“/user”)
websocket.subscribe('/user/topic/newMsg',function(response){});
接收端
@MessageMapping("/msg")
public void msg(Principal principal) {
String userId = principal.getName();
// 将这个userId在convertAndSendToUser方法中要用到
// do your sth.
}
发送端
// 这里的userId就是上面的那个,或者根据自己的实际情况用其他方法传递
messagingTemplate.convertAndSendToUser(userId,"/topic/newMsg", obj);