• SpringBoot整合WebSocket【代码】


    系列文章目录

    一、SpringBoot连接MySQL数据库实例【tk.mybatis连接mysql数据库】
    二、SpringBoot连接Redis与Redisson【代码】
    三、SpringBoot整合WebSocket【代码】
    四、SpringBoot整合ElasticEearch【代码示例】



    代码下载地址

    SpringBoot整合WebSocket【代码】


    一、效果演示

    测试链接
    在这里插入图片描述

    在这里插入图片描述

    二、引入依赖

    
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-websocketartifactId>
      <version>2.1.1.RELEASEversion>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    三、WebSocketConfig

    @Configuration
    public class WebSocketConfig {
    
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
            return new ServerEndpointExporter();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    四、SessionWrap

    SessionWrap 可根据具体需求自定义

    @Data
    public class SessionWrap {
    
        private String from;	// 连接Id
    
        private String type;	// 来凝结类型
    
        private Session session;
    
        private Date lastTime;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    五、WebSocketServer

    @Slf4j
    @Component
    @ServerEndpoint(value = "/api/websocket/{from}/{type}")
    public class WebSocketServer {
    
        @Autowired
        private MessageService messageService;
    
        public static WebSocketServer webSocketServer;
    
        // 所有的连接会话
        private static CopyOnWriteArraySet<SessionWrap> sessionList = new CopyOnWriteArraySet<>();
    
        private String from;
        private String type;
    
        @PostConstruct
        public void init() {
            webSocketServer = this;
            webSocketServer.messageService = this.messageService;
        }
    
        /**
         * @author Lee
         * @date 2023/7/18 13:57
         * @description 创建连接
         */
        @OnOpen
        public void onOpen(Session session, @PathParam(value = "from") String from, @PathParam(value = "type") String type) {
            this.from = from;
            this.type = type;
            try {
                // 遍历list,如果有会话,更新,如果没有,创建一个新的
                for (SessionWrap item : sessionList) {
                    if (item.getFrom().equals(from) && item.getType().equals(type)) {
                        item.setSession(session);
                        item.setLastTime(new Date());
                        log.info("【websocket消息】更新连接,总数为:" + sessionList.size());
                        return;
                    }
                }
                SessionWrap sessionWrap = new SessionWrap();
                sessionWrap.setFrom(from);
                sessionWrap.setType(type);
                sessionWrap.setSession(session);
                sessionWrap.setLastTime(new Date());
                sessionList.add(sessionWrap);
                log.info("【websocket消息】有新的连接,总数为:" + sessionList.size());
            } catch (Exception e) {
                log.info("【websocket消息】连接失败!错误信息:" + e.getMessage());
            }
        }
    
        /**
         * @author Lee
         * @date 2023/7/18 13:57
         * @description 关闭连接
         */
        @OnClose
        public void onClose() {
            try {
                sessionList.removeIf(item -> item.getFrom().equals(from) && item.getType().equals(type));
                log.info("【websocket消息】连接断开,总数为:" + sessionList.size());
            } catch (Exception e) {
                log.info("【websocket消息】连接断开失败!错误信息:" + e.getMessage());
            }
        }
    
        /**
         * @author Lee
         * @date 2023/7/18 14:04
         * @description 发送消息
         */
        @OnMessage
        public void onMessage(String message, Session session) {
            try {
            	// 对消息进行处理
                JSONObject r = webSocketServer.messageService.insertMessage(message);
                String userId = r.getString("userId");
                for (SessionWrap item : sessionList) {
                // 发送消息的判断逻辑可根据需求修改
                    if (item.getFrom().equals(userId) && item.getType().equals("test")) {
                        item.getSession().getBasicRemote().sendText(r.toJSONString());
                        log.info("【websocket消息】发送消息成功:" + r.toJSONString());
                    }
                }
            } catch (Exception e) {
                log.info("【websocket消息】发送消息失败!错误信息:" + e.getMessage());
            }
        }
    
        @OnError
        public void onError(Session session, Throwable error) {
    
            log.error("用户错误,原因:"+error.getMessage());
            error.printStackTrace();
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
  • 相关阅读:
    【Top101】002链表内指定区间反转
    商城项目 pc----商品详情页
    android 13.0 在自定义系统服务中通过代码设置默认laucher动态切换
    docker系列文章目录
    C/C++ extern和static的使用
    Python分享之对象的属性
    【限时福利】21天学习挑战赛 - MySQL从入门到精通
    蒙码像专属ob
    ResultSet(结果集)、Statement
    MyBatis-Plus DQL与其他知识点
  • 原文地址:https://blog.csdn.net/weixin_49832841/article/details/132779679