0

I have two Spring Boot WebSocket applications using STOMP:

  1. WebSocket server
  2. WebSocket client

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:/"; } } 

1 Answer 1

2

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:/"; } } 
Sign up to request clarification or add additional context in comments.

1 Comment

I had the exact same question. Could not find the doc you did. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.