hjl
2024-07-23 562699fa6d0c279fe0f4f81ce87c336a34a3fb91
ruoyi-service/ruoyi-admin/src/main/java/com/ruoyi/admin/sorcket/WebSocketServer.java
@@ -7,15 +7,15 @@
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
 * @author hjl
 */
@ServerEndpoint(value = "/websocket/{workerId}")
//@ServerEndpoint(value = "/websocket/{workerId}")
@Component
public class WebSocketServer {
@@ -24,7 +24,7 @@
    /**
     * 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;
    private static final AtomicInteger ONLINE_COUNT = new AtomicInteger(0);
    /**
     * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象
@@ -46,6 +46,7 @@
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("workerId") String workerId) {
        if (null != workerId && !"".equals(workerId.trim())) {
        this.session = session;
        this.userId = workerId;
        if (WEB_SOCKET_MAP.containsKey(workerId)) {
@@ -62,6 +63,14 @@
            sendMessage("socket连接成功!");
        } catch (IOException e) {
            log.error("用户:" + workerId + ",网络异常!!!!!!");
            }
        } else {
            log.info("用户 " + workerId + " 已连接: 当前在线人数为:" + getOnlineCount());
            try {
                sendMessage("socket连接失败!");
            } catch (IOException e) {
                log.error("用户:" + workerId + ",网络异常!!!!!!");
            }
        }
    }
@@ -134,14 +143,14 @@
    }
    public static synchronized int getOnlineCount() {
        return onlineCount;
        return ONLINE_COUNT.get();
    }
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
        ONLINE_COUNT.incrementAndGet();
    }
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
        ONLINE_COUNT.decrementAndGet();
    }
}