月球大数据地理空间分析展示平台-【后端】-月球后台服务
1
13693261870
2024-11-17 796b44ea813a1133beae4f3a67f1c0263510c0c7
src/main/java/com/moon/server/service/all/WebSocketService.java
@@ -11,12 +11,9 @@
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
/**
 * WebSocket服务类
 * @author WWW
 */
@ServerEndpoint(value = "/ws/select")
@Component
@SuppressWarnings("ALL")
@ServerEndpoint(value = "/ws/select")
public class WebSocketService {
    @PostConstruct
    public void init() {
@@ -27,14 +24,8 @@
    private static final AtomicInteger ONLINE_COUNT = new AtomicInteger(0);
    /**
     * 用来存放每个客户端对应的Session对象(线程安全Set)
     */
    private final static CopyOnWriteArraySet<Session> SESSION_SET = new CopyOnWriteArraySet<Session>();
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        SESSION_SET.add(session);
@@ -44,9 +35,6 @@
        sendMessage(session, "连接成功");
    }
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        SESSION_SET.remove(session);
@@ -55,48 +43,28 @@
        log.info("有连接关闭,当前连接数为:{}", cnt);
    }
    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端的消息:{}", message);
        sendMessage(session, "收到消息,消息内容:" + message);
    }
    /**
     * 出现错误
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误:{},Session ID: {}", error.getMessage(), session.getId());
    }
    /**
     * 发送消息,实践表明,每次浏览器刷新,session会发生变化。
     *
     * @param session
     * @param message
     */
    public static void sendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(String.format("%s", message));
            // session.getAsyncRemote().sendText(message)
            synchronized (session){
                session.getBasicRemote().sendText(message);
            }
        } catch (Exception ex) {
            log.error("发送消息出错:{}", ex.getMessage());
        }
    }
    /**
     * 群发消息
     *
     * @param message
     * @throws IOException
     */
    public static void broadCastInfo(String message) throws IOException {
        for (Session session : SESSION_SET) {
            if (session.isOpen()) {
@@ -105,13 +73,6 @@
        }
    }
    /**
     * 指定Session发送消息
     *
     * @param sessionId
     * @param message
     * @throws IOException
     */
    public static void sendMessage(String message, String sessionId) throws IOException {
        Session session = null;
        for (Session s : SESSION_SET) {