Spring, how to pass messages to related clients using websockets?

I am trying to use websockets in my application. I followed this guide: http://spring.io/guides/gs/messaging-stomp-websocket/

It works great.

When one of the connected clients clicks the 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 the message is sent to all connected clients.

Now I want to change the server application so that it periodically (every hour) sends messages to all my connected clients without interacting with clients.

Something like this (but this does not work explicitly):

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

thanks for the tips.

+6
source share
1 answer

@SendTo only works in SimpAnnotationMethodMessageHandler , which is only triggered through SubProtocolWebSocketHandler , hance when WebSocketMessage received from clients.

To achieve your requirements, you must introduce your @Scheduled service SimpMessagingTemplate brokerMessagingTemplate and use it directly:

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

Source: https://habr.com/ru/post/976974/


All Articles