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--;
    }
}
相关推荐
青云计划11 小时前
知光项目知文发布模块
java·后端·spring·mybatis
Victor35611 小时前
MongoDB(9)什么是MongoDB的副本集(Replica Set)?
后端
Victor35611 小时前
MongoDB(8)什么是聚合(Aggregation)?
后端
yeyeye11113 小时前
Spring Cloud Data Flow 简介
后端·spring·spring cloud
Tony Bai13 小时前
告别 Flaky Tests:Go 官方拟引入 testing/nettest,重塑内存网络测试标准
开发语言·网络·后端·golang·php
+VX:Fegn089513 小时前
计算机毕业设计|基于springboot + vue鲜花商城系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
程序猿阿伟14 小时前
《GraphQL批处理与全局缓存共享的底层逻辑》
后端·缓存·graphql
小小张说故事14 小时前
SQLAlchemy 技术入门指南
后端·python
识君啊14 小时前
SpringBoot 事务管理解析 - @Transactional 的正确用法与常见坑
java·数据库·spring boot·后端
CaracalTiger15 小时前
如何解决Unexpected token ‘<’, “<!doctype “… is not valid JSON 报错问题
java·开发语言·jvm·spring boot·python·spring cloud·json