網(wǎng)上有很多方法,這里寫一下我使用到的方法。
官方文檔:
https://docs.spring.io/spring/docs/5.2.5.RELEASE/spring-framework-reference/web.html#websocket
環(huán)境
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.
}
發(fā)送端
@Autowired
private SimpMessagingTemplate messagingTemplate;
//.....
messagingTemplate.convertAndSend("/topic/newMsg", obj);
上面這些配置是所有人都收到,如果只想發(fā)給某個人呢鼓鲁?
https://stackoverflow.com/questions/22367223/sending-message-to-specific-user-on-spring-websocket
發(fā)給某個人的配置
【如果要發(fā)給個人,一定是配置了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.
}
發(fā)送端
// 這里的userId就是上面的那個肆饶,或者根據(jù)自己的實際情況用其他方法傳遞
messagingTemplate.convertAndSendToUser(userId,"/topic/newMsg", obj);