SpringBoot整合WebSocket【代码】

系列文章目录

一、SpringBoot连接MySQL数据库实例【tk.mybatis连接mysql数据库】

二、SpringBoot连接Redis与Redisson【代码】

三、SpringBoot整合WebSocket【代码】


文章目录


代码下载地址

SpringBoot整合WebSocket【代码】


一、效果演示

测试链接

二、引入依赖

xml 复制代码
<!--    websocket    -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-websocket</artifactId>
  <version>2.1.1.RELEASE</version>
</dependency>

三、WebSocketConfig

java 复制代码
@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

四、SessionWrap

SessionWrap 可根据具体需求自定义

java 复制代码
@Data
public class SessionWrap {

    private String from;	// 连接Id

    private String type;	// 来凝结类型

    private Session session;

    private Date lastTime;
}

五、WebSocketServer

java 复制代码
@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();
    }

}
相关推荐
像少年啦飞驰点、18 小时前
零基础入门 Spring Boot:从“Hello World”到可上线微服务的完整学习指南
java·spring boot·微服务·编程入门·后端开发
indexsunny19 小时前
互联网大厂Java面试实战:从Spring Boot到微服务架构的技术问答解析
java·spring boot·redis·微服务·kafka·jwt·flyway
sheji341619 小时前
【开题答辩全过程】以 基于SpringBoot的疗养院管理系统的设计与实现为例,包含答辩的问题和答案
java·spring boot·后端
短剑重铸之日20 小时前
《设计模式》第六篇:装饰器模式
java·后端·设计模式·装饰器模式
像少年啦飞驰点、20 小时前
零基础入门 Spring Boot:从‘Hello World’到可上线微服务的完整学习路径
java·spring boot·web开发·编程入门·后端开发
1104.北光c°20 小时前
【从零开始学Redis | 第一篇】Redis常用数据结构与基础
java·开发语言·spring boot·redis·笔记·spring·nosql
码界奇点21 小时前
基于Flask与OpenSSL的自签证书管理系统设计与实现
后端·python·flask·毕业设计·飞书·源代码管理
看世界的小gui21 小时前
Jeecgboot通过Maxkey实现单点登录完整方案
java·spring boot·jeecgboot
10km21 小时前
Spring Boot 环境下使用 Map<String, MultipartFile> 实现文件上传功能
java·spring boot·mock·map·multipartfile