当前位置: 首页 > news >正文

SpringBoot整合WebSocket【代码】

系列文章目录

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


文章目录

  • 系列文章目录
  • 代码下载地址
  • 一、效果演示
  • 二、引入依赖
  • 三、WebSocketConfig
  • 四、SessionWrap
  • 五、WebSocketServer


代码下载地址

SpringBoot整合WebSocket【代码】


一、效果演示

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

在这里插入图片描述

二、引入依赖

<!--    websocket    -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId><version>2.1.1.RELEASE</version>
</dependency>

三、WebSocketConfig

@Configuration
public class WebSocketConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}
}

四、SessionWrap

SessionWrap 可根据具体需求自定义

@Data
public class SessionWrap {private String from;	// 连接Idprivate String type;	// 来凝结类型private Session session;private Date lastTime;
}

五、WebSocketServer

@Slf4j
@Component
@ServerEndpoint(value = "/api/websocket/{from}/{type}")
public class WebSocketServer {@Autowiredprivate MessageService messageService;public static WebSocketServer webSocketServer;// 所有的连接会话private static CopyOnWriteArraySet<SessionWrap> sessionList = new CopyOnWriteArraySet<>();private String from;private String type;@PostConstructpublic void init() {webSocketServer = this;webSocketServer.messageService = this.messageService;}/*** @author Lee* @date 2023/7/18 13:57* @description 创建连接*/@OnOpenpublic 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 关闭连接*/@OnClosepublic 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 发送消息*/@OnMessagepublic 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());}}@OnErrorpublic void onError(Session session, Throwable error) {log.error("用户错误,原因:"+error.getMessage());error.printStackTrace();}}
http://www.lryc.cn/news/166264.html

相关文章:

  • 微服务 第一章 Java线程池技术应用
  • 行业追踪,2023-09-14
  • 传输层协议--UDP
  • 微信会员卡开发流程
  • 《算法竞赛·快冲300题》每日一题:“点灯游戏”
  • 常见高级语言的输入与输出训练(一)
  • 恭喜!龙蜥获得 2023 大学生操作系统设计赛二等奖及特殊贡献奖
  • 中项系统集成项目管理2023上半年真题及解析
  • 实时显示当前文件夹下的文件大小,shell脚本实现
  • 7、Spring之依赖注入源码解析(下)
  • 图片码二次渲染绕过
  • 点评项目核心内容
  • 海外商城小程序为什么这么受欢迎?
  • Linux Day13 ---信号量
  • 《动手学深度学习 Pytorch版》 4.10 实战Kaggle比赛:预测比赛
  • jQuery补充
  • goaccess 日志分析 nginx
  • 认养一头牛———众筹+合伙人商业模式解析
  • 前端面试的话术集锦第 11 篇:高频考点(React和Vue两大框架)
  • 前端js下载zip文件异常问题解决
  • 深度学习面试八股文(2023.9.06)
  • Linux入门-网络基础|网络协议|OSI七层模型|TCP/IP五层模型|网络传输基本流程
  • docker系列(2) - 常用命令篇
  • Debian11安装MySQL8.0,链接Navicat
  • vue项目中使用特殊字体的步骤
  • 激光雷达检测负障碍物(附大概 C++ 代码)
  • 【每日一题】9.13 PING是怎么工作的?
  • 【Python百日进阶-Web开发-Peewee】Day279 - SQLite 扩展(四)
  • Postman接口压力测试 ---- Tests使用(断言)
  • nvue文件中@click.stop失效