gpt4 book ai didi

java - Spring 4 STOMP Websockets 心跳

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:01:38 32 4
gpt4 key购买 nike

我似乎找不到关于如何在 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);
});
};

我真的很想实现心跳,以便客户端知道谁已连接并发送一些数据以保持客户端和服务器同步。

我需要手动做吗?

最佳答案

只需调用:

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

}

关于java - Spring 4 STOMP Websockets 心跳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28841505/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com