Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring 4 STOMP Websockets Heartbeat

I can't seem to find a good resource on how to send heartbeats to clients using websockets in Spring!

I have a basic server running using this configuration:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/room");
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/channels").withSockJS();
    }
}

Then I use something like this to send messages to people who subscribed to a room:

this.simpMessagingTemplate.convertAndSend("/room/" + this.roomId, message);

This is the client code used to communicate with the server:

this.connect = function (roomNameParam, connectionCallback) {
    var socket = new SockJS('http://localhost:8080/channels'),

    self.stompClient = Stomp.over(socket);
    self.stompClient.connect({}, function (frame) {
        self.stompClient.subscribe('/room/' + roomNameParam, connectionCallback);
    });
};

I really want to implement heartbeats so the client knows who is connected and to send some data to keep the client and server in sync.

Do I need to manually do it?

like image 241
Dolan Avatar asked Mar 03 '15 20:03

Dolan


2 Answers

Just call:

.setTaskScheduler(heartBeatScheduler());

for the broker config where you want to enable it (works with simple broker too).

@Configuration
public class WebSocketMessageBrokerConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.setApplicationDestinationPrefixes("/app");
        config.enableSimpleBroker("/topic", "/queue", "/user")
                .setTaskScheduler(heartBeatScheduler());
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/endpoint");
    }

    @Bean
    public TaskScheduler heartBeatScheduler() {
        return new ThreadPoolTaskScheduler();
    }

}
like image 130
Javatar Avatar answered Oct 13 '22 18:10

Javatar


The Spring SockJS configuration contains settings for sending heartbeats. By default a heartbeat is sent every 25 seconds assuming no other messages are sent on the connection. See the Spring reference for details.

like image 24
Bogdan Avatar answered Oct 13 '22 19:10

Bogdan