Search code examples
springwebsocketwebserverstomp

How to send message to WebSocket client from Spring WebSocket server using STOMP?


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


Solution

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