package com.bohuikeji.frame.module.admin.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * 配置WebSocket
 * 对原生webSocket进行增强支持，配置支持上层消息协议STOMP，及SockJS兼容通信方式
 * @author zhengkai
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    private static long HEART_BEAT=5000;
    /**
     * 配置消息代理，支持STOMP协议
     * @param config
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        ThreadPoolTaskScheduler te = new ThreadPoolTaskScheduler();
        te.setPoolSize(1);
        te.setThreadNamePrefix("wss-heartbeat-thread-");
        te.initialize();
        //创建客户端简单消息代理，代理到已/topic为前缀的客户端
        config.enableSimpleBroker("/socket/client").setHeartbeatValue(new long[]{HEART_BEAT,HEART_BEAT}).setTaskScheduler(te);
        //创建服务端消息代理，代理到已/app为前缀的服务端点
        config.setApplicationDestinationPrefixes("/socket/server");
    }

    /**
     * 注册/gs-guide-websocket端点启用SockJS后备选项
     * 【注】：该实现用于支持在客户端不支持webSocket的情况下使用SockJS.js自动模拟webSocket,xhr-streaming,xhr-polling等实现消息双向传输，效果和webSocket相同
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/socket/connect").withSockJS();
        registry.addEndpoint("/socket/connect").setAllowedOrigins("*");
    }


}
