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