Search code examples
javaspringwebsocketstomp

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?


Solution

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