Search code examples
javaspring-mvcwebsocketspring-websocketjava-websocket

How to call @SendTo from Normal Request Call i.e @RequestMapping


I have implemented Web Socket using Spring MVC and it is working fine for me i.e work from one browser to another browser which is open for those socket using this code.

@MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public HelloMessage greeting(HelloMessage message) throws Exception {
        Thread.sleep(3000); // simulated delay
        return message;
    }

Can any one help me for who to call @SendTo("/topic/greetings") from normal api controller.I have try using this but it is not working for me

@RequestMapping(value = "/sendMessage")
    @SendTo("/topic/greetings")
    public HelloMessage sendMessage() throws Exception {
        return new HelloMessage((int) Math.random(), "This is Send From Server");
    }

any idea for this?

Thanks


Solution

  • I have found solution for that

    @Autowired
    private SimpMessagingTemplate template;
    
    
    @RequestMapping(value = "/sendMessage")
    public void sendMessage() throws Exception {
        this.template.convertAndSend("/topic/greetings", new HelloMessage(
                (int) Math.random(), "This is Send From Server"));
    }
    

    by using this we can send message to open WebSocket.

    Thanks