I have two Spring Boot WebSocket applications using STOMP:
I am able to send a WebSocket message from the client and respond to it from the server. However, now I would like to send a WebSocket message to the client triggered by an event on the server side.
Can someone tell me a way to do this?
Here is what I have now on the server side:
WebSocketConfig.java:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic/");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/alarm");
}
}
WebSocketController.java:
@Controller
public class WebSocketController {
@MessageMapping("/alarm")
@SendTo("/topic/message")
public void processMessageFromClient(@Payload String message, Principal principal) throws Exception {
System.out.println("WEBSOCKET MESSAGE RECEIVED" + message);
}
@RequestMapping(value = "/start/{alarmName}", method = RequestMethod.POST)
public String start(@PathVariable String alarmName) throws Exception {
System.out.println("Starting " + alarmName);
/* SEND MESSAGE TO WEBSOCKET CLIENT HERE */
return "redirect:/";
}
}
I found the answer on the official spring documentation.
You just need to inject a SimpMessagingTemplate
.
My controller now looks like this:
@Controller
public class WebSocketController {
private SimpMessagingTemplate template;
@Autowired
public WebSocketController(SimpMessagingTemplate template) {
this.template = template;
}
@MessageMapping("/alarm")
@SendTo("/topic/message")
public void processMessageFromClient(@Payload String message, Principal principal) throws Exception {
System.out.println("WEBSOCKET MESSAGE RECEIVED" + message);
}
@RequestMapping(value = "/start/{alarmName}", method = RequestMethod.POST)
public String start(@PathVariable String alarmName) throws Exception {
System.out.println("Starting " + alarmName);
this.template.convertAndSend("/topic/message", alarmName);
return "redirect:/";
}
}