问题
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?
回答1:
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.
回答2:
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();
}
}
回答3:
For simple broker you can config heartbeat like this:
<websocket:message-broker application-destination-prefix="/app">
<websocket:stomp-endpoint path="/wshandler" allowed-origins="*">
</websocket:stomp-endpoint>
<websocket:simple-broker prefix="/topic, /queue" heartbeat="10000,10000" scheduler="pingScheduler"/>
</websocket:message-broker>
<bean id="pingScheduler" class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">
<property name="poolSize" value="1"/>
<property name="threadNamePrefix" value="wss-heartbeat-thread-"/>
</bean>
来源:https://stackoverflow.com/questions/28841505/spring-4-stomp-websockets-heartbeat