java - Spring 4 STOMP Websockets 心跳

标签 java spring websocket stomp

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

相关文章:

java - 我如何让 ActionListener 监听按键?

java - 如何修改spring data jpa默认查询和删除?

java - 如何在 NetBeans 中使用 Hibernate 从 Mysql 获取最后一条记录?

java - 我们可以使用一个 RowMapper 对象而不是每次都创建对象来获取结果吗?

javascript - React.js 组件中 websocket 的 onopen 事件中调用函数

javascript - 当使用服务器而不是本地计算机时,我应该用什么替换 "http://localhost:3000"?

java - 包含不同对象的 2 个列表的公共(public)部分

java - 我可以在 Eclipse 中为 JAVA 创建自定义内容辅助吗?

java - 使用循环在 Java 中制作表格

python - 使用 WebSocket 以字节形式发送带有图像的 JSON