Spring,如何使用Websockets向连接的客户端广播消息?

12

我正在尝试在我的应用程序中使用WebSockets。我已经按照这个教程进行了操作:http://spring.io/guides/gs/messaging-stomp-websocket/

它完美地工作着。

当连接的客户端之一按下按钮时,将调用此方法:

@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting() throws Exception {
    System.out.println("Sending message...");
    Thread.sleep(1000); // simulated delay
    return new Greeting("hello!");        
}

并且消息被广播到所有连接的客户端。

现在我想修改我的服务器应用程序,让它定时(每小时)向所有连接的客户端广播消息,无需客户端交互。

类似于这样(但显然这不起作用):

@Scheduled(fixedRate = 3600000)
public void sendMessage(){
   try {
   @SendTo("/topic/greetings")     
   greeting();
    } catch (Exception e) {
        e.printStackTrace(); 
    }
}

谢谢您的建议。

1个回答

19
< p > @SendTo 只能在 SimpAnnotationMethodMessageHandler 中使用,该处理程序只有通过 SubProtocolWebSocketHandler 初始化时才会接收来自客户端的 WebSocketMessage

为了满足您的要求,您应该将 SimpMessagingTemplate brokerMessagingTemplate 注入到您的 @Scheduled 服务中,并直接使用它:

@Autowired
private SimpMessagingTemplate brokerMessagingTemplate;
.......
this.brokerMessagingTemplate.convertAndSend("/topic/greetings", "foo");

请您详细说明一下?我该如何注入它? - Felipe Leão
请注意我的答案中关于@Autowired的编辑。 - Artem Bilan

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