Spring 4 STOMP Websockets Heartbeat

Dolan picture Dolan · Mar 3, 2015 · Viewed 19k times · Source

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?

Answer

Javatar picture Javatar · Mar 2, 2018

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();
    }

}