Search code examples
javaspringwebsocketstomp

STOMP: Calling a method annotated with @MessageMapping not sending message to subscribed users


Followed this tutorial regarding websockets (https://www.baeldung.com/websockets-spring) and this works locally on my computer.

My issue is that calling the method directly with an endpoint (/send) does not send a message to all subscribed users, only when stompclient talks to the @MessageMapping directly.

    @MessageMapping("/liveoffers")
    @SendTo("/topic/messages")
    public OutputMessage send(final Message message) throws Exception {
        final String time = new SimpleDateFormat("HH:mm").format(new Date());
        return new OutputMessage(message.getFrom(), message.getText(), time);
    }

    @GetMapping(value = "/send")
    @ResponseStatus(HttpStatus.OK)
    public void invokeSend() throws Exception {
        send(new Message("from", "text"));
    }

Is there anyway I can call the @MessageMapping in a similar way below but actually have it functioning?


Solution

  • Have you considered using SimpMessagingTemplate to send a message instead of calling a mapped method?

    @Autowired
    SimpMessagingTemplate template;
    
    @GetMapping(value = "/send")
    @ResponseStatus(HttpStatus.OK)
    public void invokeSend() throws Exception {
        template.convertAndSend("/topic/messages", new Message("from", "text"));
    }