Spring, how to broadcast message to connected clients using websockets?

非 Y 不嫁゛ 提交于 2019-12-21 03:42:29

问题


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.


回答1:


@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");


来源:https://stackoverflow.com/questions/26465135/spring-how-to-broadcast-message-to-connected-clients-using-websockets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!