我通过 SockJS 通过 STOMP 连接到我的 Spring 后端。一切正常,配置适用于所有浏览器等。但是,我找不到发送初始消息的方法。情况如下:
- 客户端连接到主题
函数连接(){ var socket = new SockJS('http://localhost:8080/myEndpoint'); stompClient = Stomp.over(socket); stompClient.connect({}, function(frame) { 设置连接(真); console.log('已连接:' + frame); stompClient.subscribe('/topic/notify', function(message){ showMessage(JSON.parse(message.body).content); }); }); }
后端配置看起来或多或少像这样:
@配置 @EnableWebSocketMessageBroker 公共类 WebSocketAppConfig 扩展 AbstractWebSocketMessageBrokerConfigurer { ... @覆盖 公共无效 registerStompEndpoints(最终 StompEndpointRegistry 注册表){ registry.addEndpoint("/myEndpoint").withSockJS(); }
- I want to send to the client an automatic reply from the backend (on the connection event) so that I can already provide him with some dataset (e.g. read sth from the db) without the need for him (the client) to send a GET request (or any other). So to sum up, I just want to send him a message on the topic with the SimMessagingTemplate object just after he connected.
Usually I do it the following way, e.g. in a REST controller, when the template is already autowired:
@Autowired private SimpMessagingTemplate template; ... template.convertAndSend(TOPIC, new Message("it works!"));
How to achieve this on connect event?
UPDATE
I have managed to make it work. However, I am still a bit confused with the configuration. I will show here 2 configurations how the initial message can be sent:
1) First solution
JS part
stompClient.subscribe('/app/pending', function(message){
showMessage(JSON.parse(message.body).content);
});
stompClient.subscribe('/topic/incoming', function(message){
showMessage(JSON.parse(message.body).content);
});
Java part
@Controller
public class WebSocketBusController {
@SubscribeMapping("/pending")
Configuration
@Override
public void configureMessageBroker(final MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
...和其他电话
template.convertAndSend("/topic/incoming", outgoingMessage);
2)第二种解决方案
JS部分
stompClient.subscribe('/topic/incoming', function(message){
showMessage(JSON.parse(message.body).content);
})
Java部分
@Controller
public class WebSocketBusController {
@SubscribeMapping("/topic/incoming")
配置
@Override
public void configureMessageBroker(final MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
// NO APPLICATION PREFIX HERE
}
...和其他电话
template.convertAndSend("/topic/incoming", outgoingMessage);
概括:
第一种情况使用两个订阅——我想避免这种情况,并认为这可以只用一个来管理。
然而,第二个没有应用前缀。但至少我可以有一个订阅来收听提供的主题以及发送初始消息。