如何从普通请求调用@SendTo,即@RequestMapping?

16

我已经使用Spring MVC实现了Web Socket,对我来说它运行良好,即使用此代码将工作从一个浏览器传输到另一个打开的浏览器中的那些套接字。

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

有人能帮我吗,如何从普通API控制器调用@SendTo("/topic/greetings")。 我尝试过这样做,但对我无效。

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

有什么想法吗?

谢谢

1个回答

22

我已经找到了解决方案。

@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。
谢谢。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接