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();
                    }
                }
            }
        }
    

}

测试

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

相关推荐
diving deep6 小时前
springboot集成日志配置文件
java·spring boot·后端·logback
lkx097887 小时前
第九天的尝试
python
佩奇的技术笔记7 小时前
Python入门手册:Python基础语法
开发语言·python
源码云商7 小时前
基于 SpringBoot + Vue 的海滨体育馆管理系统设计与实现
vue.js·spring boot·后端
白白糖8 小时前
相同,对称,平衡,右视图(二叉树)
python·算法·二叉树·力扣
学习baba酱8 小时前
关于Python+selenium+chrome编译为exe更换电脑无法打开问题
chrome·python·selenium
几道之旅8 小时前
pytdx数据获取:在线获取和离线获取(8年前的东西,还能用吗?)
python
Uranus^9 小时前
深入解析Spring Boot与Spring Cloud在微服务架构中的实践与应用
java·spring boot·spring cloud·微服务·分布式系统
jay神9 小时前
基于Python+YOLO模型的手势识别系统
开发语言·python·深度学习·yolo·手势识别系统
点云兔子9 小时前
使用 OpenCV 实现 ArUco 码识别与坐标轴绘制
人工智能·python·opencv