如何从普通请求调用即@RequestMapping调用@SendTo
问题内容:
我已经使用Spring MVC实现了Web套接字,它对我来说很好用,即从一个浏览器到另一个浏览器都可以使用此代码为那些套接字打开。
@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");
}
有什么想法吗?
谢谢
问题答案:
我已经找到解决方案
@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。
谢谢