问题描述
我正在尝试在我的应用程序中使用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();
}
}
谢谢.
@SendTo
仅在SimpAnnotationMethodMessageHandler
中起作用,SimpAnnotationMethodMessageHandler
仅通过SubProtocolWebSocketHandler
启动,以防从客户端收到WebSocketMessage
./p>
要达到您的要求,您应该注入@Scheduled
服务SimpMessagingTemplate brokerMessagingTemplate
并直接使用它:
@Autowired
private SimpMessagingTemplate brokerMessagingTemplate;
.......
this.brokerMessagingTemplate.convertAndSend("/topic/greetings", "foo");
I am trying to use websockets in my app. I have followed this tutorial: http://spring.io/guides/gs/messaging-stomp-websocket/
It works perfectly.
When one of connected clients press button, this method is called:
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting() throws Exception {
System.out.println("Sending message...");
Thread.sleep(1000); // simulated delay
return new Greeting("hello!");
}
and message is broadcasted to all of connected clients.
Now i want to modify my server app, that it will broadcast messages periodically (each hour) to all of my connected clients, without interaction from clients.
Something like this(but this is not working obviously):
@Scheduled(fixedRate = 3600000)
public void sendMessage(){
try {
@SendTo("/topic/greetings")
greeting();
} catch (Exception e) {
e.printStackTrace();
}
}
Thx for advices.
@SendTo
works only in the SimpAnnotationMethodMessageHandler
, which is initiated only through the SubProtocolWebSocketHandler
, hance when the WebSocketMessage
is received from clients.
To achieve your requirements you should inject to the your @Scheduled
service SimpMessagingTemplate brokerMessagingTemplate
and use it directly:
@Autowired
private SimpMessagingTemplate brokerMessagingTemplate;
.......
this.brokerMessagingTemplate.convertAndSend("/topic/greetings", "foo");
这篇关于春天,如何使用websockets向连接的客户端广播消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!