WebSorcket 集成 Spring Boot

WebSorcket 集成 Spring Boot

配置

java 复制代码
@Configuration
public class WebSocketConfiguraion {
    @Bean
    public ServerEndpointExporter serverEndpointExporter (){

        ServerEndpointExporter exporter = new ServerEndpointExporter();

        return exporter;
    }
}

服务类

java 复制代码
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.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket")
@Slf4j
public class WebSocketServer {
    
        /**
         * 线程安全的无序的集合
         */
        private static final CopyOnWriteArraySet<Session> SESSIONS = new CopyOnWriteArraySet<>();

        /**
         * 存储在线连接数
         */
        private static final Map<String, Session> SESSION_POOL = new HashMap<>();

        @OnOpen
        public void onOpen(Session session, @PathParam(value = "userId") String userId) {
            try {
                SESSIONS.add(session);
                SESSION_POOL.put(userId, session);
                log.info("【WebSocket消息】有新的连接,总数为:" + SESSIONS.size());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @OnClose
        public void onClose(Session session) {
            try {
                SESSIONS.remove(session);
                log.info("【WebSocket消息】连接断开,总数为:" + SESSIONS.size());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @OnMessage
        public void onMessage(String message) {
            log.info("【WebSocket消息】收到客户端消息:" + message);
        }

        /**
         * 此为广播消息
         *
         * @param message 消息
         */
        public void sendAllMessage(String message) {
            log.info("【WebSocket消息】广播消息:" + message);
            for (Session session : SESSIONS) {
                try {
                    if (session.isOpen()) {
                        session.getAsyncRemote().sendText(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        /**
         * 此为单点消息
         *
         * @param userId  用户编号
         * @param message 消息
         */
        public void sendOneMessage(String userId, String message) {
            Session session = SESSION_POOL.get(userId);
            if (session != null && session.isOpen()) {
                try {
                    synchronized (session) {
                        log.info("【WebSocket消息】单点消息:" + message);
                        session.getAsyncRemote().sendText(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        /**
         * 此为单点消息(多人)
         *
         * @param userIds 用户编号列表
         * @param message 消息
         */
        public void sendMoreMessage(String[] userIds, String message) {
            for (String userId : userIds) {
                Session session = SESSION_POOL.get(userId);
                if (session != null && session.isOpen()) {
                    try {
                        log.info("【WebSocket消息】单点消息:" + message);
                        session.getAsyncRemote().sendText(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    

}

测试

注意:项目安全框架白名单放行

相关推荐
mldong12 分钟前
工作流引擎的退回修改:金额从 6666 改成 666,重提还是回到退回它的那个人
后端·架构
陈随易13 分钟前
一个网吧网管,做了个网页,卖了 5000 万
前端·后端·程序员
captain3768 小时前
MyBatis(入门5)其他查询操作
java·数据库·spring boot·mybatis
前端精髓9 小时前
结构化输出with_structured_output(抽卡)
python·langchain
深蓝AI10 小时前
Python 3.13 的 Queue.shutdown:异步消费者终于能正常收工了
后端
尹人入圣10 小时前
目前热门的IP驱动产业新场景新工具
网络·python·网络协议·tcp/ip
武子康10 小时前
MultiNet6 空闲崩溃:`EXCVADDR=0x8` 后又出现 `CORRUPT HEAP`
人工智能·后端·agent
Nuanyt11 小时前
Agent 学习笔记(下篇三):上线工程、进阶选择与操作界面(Stage 7 / 7.5 / 8 + 延伸路线)
笔记·python·学习·memory·aiagent·harness
吴卫斌11 小时前
定投ETF实战指南(四):行业/主题ETF——定投的“进攻端“
开发语言·python·股票·量化
2601_9679873711 小时前
Python——入门级(定义功能def函数)
python·函数·可变参数·默认参数·关键字参数