13

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

4

1 回答 1

19

我已经找到了解决方案

@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"));
}

通过使用它,我们可以发送消息以打开 WebSocket。

谢谢

于 2015-07-24T11:31:28.260 回答