我似乎找不到如何在Spring中使用websockets向客户端发送心跳的好资源!
我有一个使用此配置运行的基本服务器:
@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();
}
}
然后我使用这样的东西向订阅房间的人发送消息:
this.simpMessagingTemplate.convertAndSend("/room/" + this.roomId, message);
这是用于与服务器通信的客户端代码:
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);
});
};
我真的想实现心跳,以便客户端知道谁连接并发送一些数据以保持客户端和服务器同步。
我需要手动操作吗?
Spring SockJS配置包含发送心跳的设置。默认情况下,假设连接上没有发送其他消息,则每25秒发送一次心跳。有关详细信息,请参阅the Spring reference。
只需致电:
.setTaskScheduler(heartBeatScheduler());
对于要启用它的代理配置(也适用于简单代理)。
@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();
}
}
对于简单的代理,您可以像这样配置心跳:
<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>