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

Springboot+Websocket+Security+Vue 实现弹幕推送功能

后端部分 (Spring Boot)

1. 创建一个 Spring Boot 项目

创建一个新的 Spring Boot 项目并添加以下依赖:

<dependencies><!-- Spring Boot Starter Web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Spring Boot Starter WebSocket --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency><!-- Spring Security --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><!-- Spring Boot Starter Thymeleaf (optional for views) --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
</dependencies>
2. 配置 WebSocket

在配置类中启用 WebSocket 支持并配置 WebSocket 端点:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {@Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {registry.addHandler(new MyWebSocketHandler(), "/ws").setAllowedOrigins("*");}
}
3. 创建 WebSocket 处理器
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;public class MyWebSocketHandler extends TextWebSocketHandler {@Overrideprotected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {// 广播消息给所有连接的客户端for (WebSocketSession webSocketSession : sessions) {webSocketSession.sendMessage(message);}}
}
4. 配置 Spring Security

设置一个基本的安全配置:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/").permitAll().anyRequest().authenticated().and().csrf().disable() // 在开发阶段可以禁用 CSRF.formLogin().permitAll().and().logout().permitAll();}
}

前端部分 (Vue)

1. 创建一个 Vue 项目

使用 Vue CLI 创建一个新的 Vue 项目:

vue create my-project
2. 安装 Vue WebSocket 插件

安装 vue-native-websocket 插件:

npm install vue-native-websocket
3. 配置 WebSocket

main.js 中配置 WebSocket:

import Vue from 'vue'
import App from './App.vue'
import VueNativeSock from 'vue-native-websocket'Vue.config.productionTip = falseVue.use(VueNativeSock, 'ws://localhost:8080/ws', {format: 'json'
})new Vue({render: h => h(App),
}).$mount('#app')
4. 创建弹幕组件

components 文件夹中创建一个 Danmaku.vue 组件:

<template><div class="danmaku"><input v-model="message" @keyup.enter="sendMessage" placeholder="输入弹幕" /><ul><li v-for="msg in messages" :key="msg">{{ msg }}</li></ul></div>
</template><script>
export default {data() {return {message: '',messages: []}},sockets: {onmessage(data) {this.messages.push(data)}},methods: {sendMessage() {this.$socket.send(this.message)this.message = ''}}
}
</script><style scoped>
.danmaku {position: fixed;bottom: 10px;width: 100%;display: flex;flex-direction: column;align-items: center;
}
input {width: 80%;padding: 10px;margin-bottom: 10px;
}
ul {list-style: none;padding: 0;
}
li {background: rgba(0, 0, 0, 0.5);color: white;padding: 5px 10px;margin: 5px 0;border-radius: 5px;animation: danmakuMove 10s linear infinite;
}
@keyframes danmakuMove {from {transform: translateX(100%);}to {transform: translateX(-100%);}
}
</style>

集成和测试

  1. 启动 Spring Boot 应用。
  2. 启动 Vue 应用。
  3. 打开浏览器访问 Vue 应用,输入弹幕消息,确认消息通过 WebSocket 广播并显示在页面上。
http://www.lryc.cn/news/416234.html

相关文章:

  • LangChain之网络爬虫
  • VueRouter 相关信息
  • [环境配置]Pycharm:Failed to start [PowerShell.exe]
  • 搜狗爬虫(www.sogou.com)IP及UA,真实采集数据
  • 北京青蓝智慧科技ITSS服务经理:长安链ChainBridge“链桥”问世 加速国家级区块链网络互联互通
  • 音视频入门基础:WAV专题(5)——FFmpeg源码中解码WAV Header的实现
  • 爬虫:csv存储:写入和读取
  • Opencv-绘制几何图形
  • ElasticSearch安装与集群部署
  • 盘点12款企业常用源代码加密软件,源代码防泄密很重要!
  • 文件上传和下载
  • 机械学习—零基础学习日志(高数22——泰勒公式理解深化)
  • Java | Leetcode Java题解之第318题最大单词长度乘积
  • 科普文:JUC系列之多线程门闩同步器Condition的使用和源码解读
  • Stable Diffusion绘画 | 图生图-基础使用介绍—提示词反推
  • 正点原子imx6ull-mini-Linux驱动之Linux SPI 驱动实验(22)
  • TypeScript 函数
  • C++ : namespace,输入与输出,函数重载,缺省参数
  • 目标检测 | yolov1 原理和介绍
  • excel中有些以文本格式存储的数值如何批量转换为数字
  • 原神升级计划数据表:4个倒计时可以修改提示信息和时间,可以点击等级、命座、天赋、备注进行修改。
  • YoloV10 论文翻译(Real-Time End-to-End Object Detection)
  • 第R1周:RNN-心脏病预测
  • Golang | Leetcode Golang题解之第321题拼接最大数
  • 远程连接本地虚拟机失败问题汇总
  • WebRTC 初探
  • Python:read,readline和readlines的区别
  • 重生之我学编程
  • 如何将PostgreSQL的数据实时迁移到SelectDB?
  • 关于c语言的const 指针