springboot 使用websocket

简介:在springboot中使用websocket

1、引入依赖

java 复制代码
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2、创建ServerEndpoint服务

java 复制代码
@ServerEndpoint(value = "/websocket/team")
@Component
public class MyWebSocketHandler {


    //保存所有在线socket连接
    private static Map<String, MyWebSocketHandler> webSocketMap = new LinkedHashMap<>();

    //记录当前在线数目
    private static int count = 0;

    //当前连接(每个websocket连入都会创建一个MyWebSocket实例
    private Session session;

    //处理连接建立
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketMap.put(session.getId(), this);
        addCount();
    }

    //接受消息
    @OnMessage
    public void onMessage(String message, Session session) {
        //从上下中获取对象 无法通过注解获取,因为websocket中会报空指针异常
        ApplicationContext context = ApplicationContextRegister.getApplicationContext();
        //将string转成JSON对象
        JSONObject entries = JSONUtil.parseObj(message);
        //将JSON对象转成bean对象
        WebsocketJson websocketJson = entries.toBean(WebsocketJson.class);
        switch (websocketJson.getType()) {
            case "1": {
                //创建房间
                BankFacadeServiceImpl facadeService = context.getBean(BankFacadeServiceImpl.class);
                //业务逻辑
                break;
            }
            case "2": {
                //加入队伍
                websocketJson.setSessionId(session.getId());
                BankFacadeServiceImpl facadeService = context.getBean(BankFacadeServiceImpl.class);
                //业务逻辑
                break;
            }
            case "3": {
                //退出队伍
                websocketJson.setSessionId(session.getId());
                BankFacadeServiceImpl facadeService = context.getBean(BankFacadeServiceImpl.class);
                //业务逻辑
                break;
            }
            case "4": {
                //创建试卷
                BankFacadeServiceImpl facadeService = context.getBean(BankFacadeServiceImpl.class);
                //业务逻辑
                break;
            }
            case "5": {
                //业务逻辑
                break;
            }
            case "6": {
                //业务逻辑
                break;
            }
            case "7":{
                try {
                    sendMessage("心跳检测");
                }catch (Exception e){
                    System.out.println(e.getMessage());
                }
                break;
            }
        }

    }

    //处理错误
    @OnError
    public void onError(Throwable error, Session session) {
//        log.info("发生错误{},{}",session.getId(),error.getMessage());
    }

    //处理连接关闭
    @OnClose
    public void onClose() {
        webSocketMap.remove(this.session.getId());
        reduceCount();
    }

    //组队消息
    public void sendMessageJson(WebsocketJson message, MyWebSocketHandler handler) {
        try {
            if (handler == null) {
                this.session.getBasicRemote().sendText(JSONUtil.toJsonStr(JSONUtil.parse(message)));
            } else {
                handler.sendMessage(JSONUtil.toJsonStr(JSONUtil.parse(message)));
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
            throw new RuntimeException(e);
        }

    }

    //发送消息
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    //广播消息
    public static void broadcast() {
        MyWebSocketHandler.webSocketMap.forEach((k, v) -> {
            try {
                v.sendMessage("这是一条测试广播");
            } catch (Exception e) {
            }
        });
    }

    //操作count,使用synchronized确保线程安全
    public static synchronized void addCount() {
        MyWebSocketHandler.count++;
    }

    public static synchronized void reduceCount() {
        MyWebSocketHandler.count--;
    }
}
相关推荐
怕浪猫4 小时前
FDE 如何正确解决现场项目工程性的问题
前端·后端·ai编程
GreenTea4 小时前
vLLM 与 SGLang KV Cache 底层实现机制深度调研报告
前端·后端·算法
考虑考虑4 小时前
Java实现hmacsha256加密算法
java·后端·java ee
MetaLite5 小时前
SpringBoot接口分层规范-外网网关内部服务与参数边界
java·数据库·spring boot
凤山老林5 小时前
聊聊企业级 API 安全:Spring Boot 落地 OAuth 2.1、mTLS 与接口签名防篡改
spring boot·后端·安全·oauth
林鹿6 小时前
maven属性与groovy变量对照表
后端
烽火戏诸诸诸侯6 小时前
AI 让我的独门小工具焕发第二春
后端·ai编程·vibecoding
狼爷7 小时前
硅谷爆火的FDE是AI新风口,还是高级外包?
后端·全栈
xinjia_ctrl8 小时前
暑假实习总结
git·后端·spring·maven·intellij-idea
IT_陈寒10 小时前
Java Stream处理大集合,我的内存怎么就炸了
前端·人工智能·后端