package com.ag.web.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by WangN on 2019/3/31
 *  websocket拦截器，处理业务
 */
public class AgWebSocketHander extends TextWebSocketHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(AgWebSocketHander.class);

    //保存用户链接   采用线程安全的 ConcurrentHashMap
    private static ConcurrentHashMap<String, WebSocketSession> userSession;

    static {
        userSession =  new ConcurrentHashMap<>();
    }

    public static ConcurrentHashMap<String, WebSocketSession> getUserSession() {
        return userSession;
    }

    public static void setUserSession(ConcurrentHashMap<String, WebSocketSession> userSession) {
        AgWebSocketHander.userSession = userSession;
    }

    //链接就绪
    @Override
    public synchronized void afterConnectionEstablished(WebSocketSession session) throws Exception {
        if (userSession!=null){
            userSession.put((String)session.getAttributes().get("sys.user"),session);
        }
       // super.afterConnectionEstablished(session);
    }
    // 处理信息
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
    }
    // 处理传输时异常
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        LOGGER.info("关闭websocket连接");
        String userId= (String) session.getAttributes().get("sys.user");
        LOGGER.info("用户"+userId+"已退出！");
        userSession.remove(userId);
    }
}