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

spring-websocket在SpringBoot(包含SpringSecurity)项目中的导入

✅作者简介:大家好,我是 Meteors., 向往着更加简洁高效的代码写法与编程方式,持续分享Java技术内容。
🍎个人主页:Meteors.的博客
🥭本文内容:spring-websocket在SpringBoot(包含SpringSecurity)项目中的导入

-----------------------------------------------------       目录       ----------------------------------------------------------

目录

一、背景

二、导入实现

1. 后端:pom文件中导入依赖

2.后端:编写后端配置类

3. 后端:编写消息容器与消息处理类

4. 前端:VUE3测试代码

(1) 下载依赖

(2)将测试代码粘贴到空的.vue文件中

4. 测试连接网站:在线网址测试

三、 结果展示


---------------------------------------------------------------------------------------------------------------------------------

一、背景

        最近在项目中想实现实时性比较强的功能,在网上搜索之后发现,推荐websocket实现的比较多,然后也发现spring有对websocket进行包装的类,所以想使用websocket。

二、导入实现

1. 后端:pom文件中导入依赖

        <!--        WebSocket代码依赖          --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>

2.后端:编写后端配置类

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {@Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {// 注册WebSocket处理器和端点registry.addHandler(new WebSocketHandler(), "/websocket")   // 注册WebSocket处理器,指定处理路径.setAllowedOrigins("*");    // 设置允许的跨域origin(可选)}}

3. 后端:编写消息容器与消息处理类

package com.ruoyi.schooltimetable.websocket;import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;import java.util.ArrayList;
import java.util.List;@Component
public class WebSocketHandler extends TextWebSocketHandler {private List<WebSocketSession> sessions = new ArrayList<>();public void add(WebSocketSession session) {sessions.add(session);}public void remove(WebSocketSession session) {sessions.remove(session);}@Overridepublic void afterConnectionEstablished(WebSocketSession session) throws Exception {// 当 WebSocket 连接建立成功后执行该方法System.err.println("------------   连接完成   ------------");// 保存 WebSocketSession 到某个容器中,方便后续处理sessions.add(session);// 发送欢迎消息给客户端String welcomeMessage = "欢迎连接WebSocket服务器!";TextMessage textMessage = new TextMessage(welcomeMessage);session.sendMessage(textMessage);}@Overridepublic void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {// 当接收到客户端发送的WebSocket消息时执行该方法// 获取消息内容String receivedMessage = message.getPayload().toString();// 处理消息,如解析消息内容、发送响应等//// 发送响应给客户端String response = "收到您的消息:" + receivedMessage;TextMessage textMessage = new TextMessage(response);session.sendMessage(textMessage);}@Overridepublic void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {// 当WebSocket传输发生错误时执行该方法// 处理错误,如记录日志、关闭连接等//// 关闭WebSocket连接session.close();}@Overridepublic void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {// 当WebSocket连接关闭后执行该方法System.err.println("---------------   断开成功   ---------------");// 清理操作,如释放资源、通知其他用户等// 从容器中移除WebSocketSessionsessions.remove(session);}
}

如果是在springsecurity中进行配置,需要在SpringSecurity配置类中对websocket的接口进行放行,不然会连接失败。位置:

4. 前端:VUE3测试代码

(1) 下载依赖

执行:

npm install websocket

(2)将测试代码粘贴到空的.vue文件中

<template><div>WebSocket Example<button @click="connect">Connect</button><button @click="disconnect">Disconnect</button><button @click="sendMessage">Send Message</button></div>
</template><script>
// import { ref } from 'vue';export default {name: 'WebSocketExample',data() {return {socket: null,message: '',receivedMessage: ''};},methods: {connect() {if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {alert('111')this.socket = new WebSocket('ws://localhost:8095/websocket');this.socket.onopen = () => {alert('WebSocket connected')console.log('WebSocket connected');};this.socket.onmessage = (event) => {this.receivedMessage = event.data;};this.socket.onclose = () => {console.log('WebSocket disconnected');};}},disconnect() {if (this.socket && this.socket.readyState === WebSocket.OPEN) {this.socket.close();}},sendMessage() {if (this.socket && this.socket.readyState === WebSocket.OPEN) {this.socket.send(this.message);}}}
};
</script>

4. 测试连接网站:在线网址测试

测试网址:

Websocket在线测试-Websocket接口测试-Websocket模拟请求工具Websocket模拟请求工具:在线Websocket测试工具,Websocket接口测试,外网内网通用Websocket请求测试,内网测试环境填入内网服务端IP和端口即可,在线模拟Websocket请求在线工具http://www.yunjson.com/websocket/

三、 结果展示

  • 在VUE中测试连接:·
  • 在测试网址中测试连接:

  • 后端控制台的显示:

最后,

有问题可以打在评论区,希望文章对你有所帮助...!

http://www.lryc.cn/news/95371.html

相关文章:

  • SpringBoot + Vue前后端分离项目实战 || 六:Jwt加密整合配置
  • WPF 如何设置全局的订阅发布事件
  • STM32 USB使用记录:HID类设备(前篇)
  • 探索AI图像安全,助力可信AI发展
  • vue 学习笔记 【ElementPlus】el-menu 折叠后图标不见了
  • 【JavaEE初阶】HTTP协议
  • 基于SaaS模式的Java基层卫生健康云HIS系统源码【运维管理+运营管理+综合监管】
  • effective c++ 条款2
  • Python爬虫之Scrapy框架系列(23)——分布式爬虫scrapy_redis浅实战【XXTop250部分爬取】
  • html基于onmouse事件让元素变颜色
  • Linux环境PostgreSQL安装
  • Rust 数据类型 之 结构体(Struct)
  • 数据结构之Queue的实现
  • rust声明式宏
  • 第二章:Learning Deep Features for Discriminative Localization ——学习用于判别定位的深度特征
  • 【CSS】box-shadow 属性
  • 基于深度学习的高精度课堂人脸检测系统(PyTorch+Pyside6+YOLOv5模型)
  • Mysql错误日志、通用查询日志、二进制日志和慢日志的介绍和查看
  • 【Linux】Tcp服务器的三种与客户端通信方法及守护进程化
  • 【Spring Cloud】git 仓库新的配置是如何刷新到各个微服务的原理步骤
  • 三,创建订单微服务消费者 第三章
  • 【雕爷学编程】Arduino动手做(87)---ULN2003步进电机模组2
  • 【C#】微软的Roslyn 是个啥?
  • 两个小封装电机驱动芯片:MLX813XX、A4950
  • 数据结构【绪论】
  • 掌握无人机遥感数据预处理的全链条理论与实践流程、典型农林植被性状的估算理论与实践方法、利用MATLAB进行编程实践(脚本与GUI开发)以及期刊论文插图制作等
  • Angular中组件设计需要注意什么?
  • 电容触摸屏(TP)的工艺结构
  • Qt小妙招:如何在可执行文件生成后,在pro文件中添加其他命令操作?
  • 做好防雷检测的意义和作用