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.
In order to tell Spring to forward client requests to the endpoint , we need to register the handler. Start the application- Go to http://localhost:8080 Click on start new chat it opens the WebSocket connection. Type text in the textbox and click send. On clicking end chat, the WebSocket connection will be closed.
To build the WebSocket server-side, we will utilize the Spring Boot framework which significantly speeds up the development of standalone and web applications in Java. Spring Boot includes the spring-WebSocket module, which is compatible with the Java WebSocket API standard (JSR-356).
STOMP, an acronym for Simple Text Oriented Messaging Protocol, is a simple HTTP-like protocol for interacting with any STOMP message broker. Any STOMP client can interact with the message broker and be interoperable among languages and platforms.
@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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With