管道基础大数据平台系统开发-【后端】-Server
13693261870
2024-03-25 b6b0cb226fcf184525ee7b36af3a09471e9c0057
src/main/java/com/lf/server/service/all/WebSocketService.java
@@ -15,7 +15,7 @@
 * WebSocket服务类
 * @author WWW
 */
@ServerEndpoint(value = "/ws")
@ServerEndpoint(value = "/ws/select")
@Component
public class WebSocketService {
    @PostConstruct
@@ -23,21 +23,21 @@
        System.out.println("websocket 加载");
    }
    private static Logger log = LoggerFactory.getLogger(WebSocketService.class);
    private final static Logger log = LoggerFactory.getLogger(WebSocketService.class);
    private static final AtomicInteger ONLINE_COUNT = new AtomicInteger(0);
    /**
     * 用来存放每个客户端对应的Session对象(线程安全Set)
     */
    private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();
    private final static CopyOnWriteArraySet<Session> SESSION_SET = new CopyOnWriteArraySet<Session>();
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        SessionSet.add(session);
        SESSION_SET.add(session);
        int cnt = ONLINE_COUNT.incrementAndGet();
        log.info("有连接加入,当前连接数为:{}", cnt);
@@ -49,7 +49,7 @@
     */
    @OnClose
    public void onClose(Session session) {
        SessionSet.remove(session);
        SESSION_SET.remove(session);
        int cnt = ONLINE_COUNT.decrementAndGet();
        log.info("有连接关闭,当前连接数为:{}", cnt);
@@ -75,7 +75,6 @@
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误:{},Session ID: {}", error.getMessage(), session.getId());
        error.printStackTrace();
    }
    /**
@@ -87,9 +86,8 @@
    public static void sendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(String.format("%s", message));
        } catch (IOException e) {
            log.error("发送消息出错:{}", e.getMessage());
            e.printStackTrace();
        } catch (Exception ex) {
            log.error("发送消息出错:{}", ex.getMessage());
        }
    }
@@ -100,7 +98,7 @@
     * @throws IOException
     */
    public static void broadCastInfo(String message) throws IOException {
        for (Session session : SessionSet) {
        for (Session session : SESSION_SET) {
            if (session.isOpen()) {
                sendMessage(session, message);
            }
@@ -116,7 +114,7 @@
     */
    public static void sendMessage(String message, String sessionId) throws IOException {
        Session session = null;
        for (Session s : SessionSet) {
        for (Session s : SESSION_SET) {
            if (s.getId().equals(sessionId)) {
                session = s;
                break;
@@ -126,7 +124,7 @@
        if (session != null) {
            sendMessage(session, message);
        } else {
            log.warn("没有找到你指定ID的会话:{}", sessionId);
            log.info("没有找到你指定ID的会话:{}", sessionId);
        }
    }
}