package com.gz.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 在线WebSocket
 * @author LiuchangLan
 * @date 2020/8/7 10:02
 */
@ServerEndpoint("/webSocket/{adminId}")
@Component
@Slf4j
public class WebSocketServer {

    /**
     * @description 存放所有在线的客户端 static保证线程安全
     * @author LiuChangLan
     * @since 2020/8/7 10:03
     */
    public static Map<String, Session> clients = new ConcurrentHashMap<>();

    /**
     * @description 连接
     * @author LiuChangLan
     * @since 2020/8/7 10:09
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("adminId")String adminId){
        clients.put(adminId,session);
        log.info("客户端{}连接了 当前在线人数：{}",adminId,clients.size());
    }

    /**
     * @description 断开连接
     * @author LiuChangLan
     * @since 2020/8/7 10:09
     */
    @OnClose
    public void onClose(Session session, @PathParam("adminId")String adminId){
        clients.remove(adminId);
        log.info("客户端{}断开了 当前在线人数：{}",adminId,clients.size());
    }

    /**
     * @description 发送错误
     * @author LiuChangLan
     * @since 2020/8/7 10:09
     */
    @OnError
    public void onError(Throwable throwable){
        throwable.printStackTrace();
    }

    /**
     * @description 接受消息
     * @author LiuChangLan
     * @since 2020/8/7 10:09
     */
    @OnMessage
    public void onMessage(@PathParam("adminId")String adminId, String message){
        log.info("服务端收到客户端{}发来的消息: {}",adminId, message);
    }

    public void sendMessage(String adminId,String message){
        Session session = clients.get(adminId);
        if (session != null){
            session.getAsyncRemote().sendText(message);
        }
    }

}
