package cn.wise.sc.cement.business.config;

import org.apache.catalina.session.StandardSessionFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;

@Configuration
public class WebSocketConfig extends ServerEndpointConfig.Configurator {

	private static final Logger log = LoggerFactory.getLogger(WebSocketConfig.class);

	/**
	 * 修改握手信息
	 */
	@Override
	public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
		StandardSessionFacade ssf = (StandardSessionFacade) request.getHttpSession();
		if (ssf != null) {
			HttpSession httpSession = (HttpSession) request.getHttpSession();
			//关键操作
			sec.getUserProperties().put("sessionId", httpSession.getId());
			log.info("获取到的SessionID：" + httpSession.getId());
		}
		super.modifyHandshake(sec, request, response);

	}

	/**
	 * WebSocket的支持 b
	 *
	 * @return
	 */
	@Bean
	public ServerEndpointExporter serverEndpointExporter() {
		//这个对象说一下，貌似只有服务器是tomcat的时候才需要配置,具体我没有研究
		return new ServerEndpointExporter();
	}

}
