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--;
    }
}
相关推荐
小江的记录本19 小时前
【泛型】泛型:泛型擦除、通配符、上下界限定
java·windows·spring boot·后端·spring·maven·mybatis
pupudawang19 小时前
springboot下使用druid-spring-boot-starter
java·spring boot·后端
lierenvip19 小时前
Spring Boot 自动配置
java·spring boot·后端
didiplus1 天前
Python 入门第一课:为什么选择 Python?3 分钟搭建你的第一个程序
后端
dreamxian1 天前
苍穹外卖day11
java·spring boot·后端·spring·mybatis
华科易迅1 天前
Spring装配对象方法-注解
java·后端·spring
AwesomeDevin1 天前
AI时代,我们的任务不应沉溺于与 AI 聊天,🤔 从“对话式编程”迈向“数字软件工厂”
前端·后端·架构
Victor3561 天前
MongoDB(60)如何使用explain命令?
后端
Victor3561 天前
MongoDB(59)如何分析查询性能?
后端