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--;
    }
}
相关推荐
小码哥_常1 天前
Spring Boot 搭建邮件发送系统:开启你的邮件自动化之旅
后端
石榴树下的七彩鱼1 天前
图片修复 API 接入实战:网站如何自动去除图片水印(Python / PHP / C# 示例)
图像处理·后端·python·c#·php·api·图片去水印
我叫黑大帅1 天前
为什么TCP是三次握手?
后端·网络协议·面试
我叫黑大帅1 天前
如何排查 MySQL 慢查询
后端·sql·面试
techdashen1 天前
Rust项目公开征测:Cargo 构建目录新布局方案
开发语言·后端·rust
一 乐1 天前
电影院|基于springboot + vue电影院购票管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·电影院购票管理管理系统
消失的旧时光-19431 天前
Spring Boot 实战(五):接口工程化升级(统一返回 + 异常处理 + 错误码体系 + 异常流转机制)
java·spring boot·后端·解耦
Rust研习社1 天前
Rust 智能指针 Cell 与 RefCell 的内部可变性
开发语言·后端·rust
夕颜1111 天前
Skill 机器人 vs Hermes Agent:两种「AI 越用越聪明」的路径
后端
IT_陈寒1 天前
SpringBoot自动配置把我都整不会了
前端·人工智能·后端