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>
集成和测试
- 启动 Spring Boot 应用。
- 启动 Vue 应用。
- 打开浏览器访问 Vue 应用,输入弹幕消息,确认消息通过 WebSocket 广播并显示在页面上。