Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

spring

stomp

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.

like image 424
Michael Avatar asked Oct 20 '14 11:10

Michael


People also ask

How do you use WebSockets in spring?

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.

Does spring boot support WebSocket?

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).

What is STOMP in WebSockets?

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.


1 Answers

@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");
like image 169
Artem Bilan Avatar answered Oct 21 '22 16:10

Artem Bilan