如何从普通请求调用(即@RequestMapping)调用@SendTo

2024-04-30

我已经使用 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");
    }

有什么想法吗?

Thanks


我已经找到了解决方案

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

Thanks

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从普通请求调用(即@RequestMapping)调用@SendTo 的相关文章

随机推荐