需求
- 实时弹幕不需要数据库存储
- 工具vue+springboot
实现
效果图:
前端代码:
实现原理:利用transition-group组件实现群动画效果(需绑定一个数组),然后在随机给每一个弹幕一个高度即可。在通过即时通信给数组添加数据即可随机高度出现弹幕。
技术要求:transition-group(建议参照vue官方文档),axios(需要解决跨域问题),socket
代码:
<!--yzx-->
<template>
<div id="test">
<label for="">
弹幕:
<input type="text" v-model="id">
</label>
<input type="button" value="button" @click="add"><br><br><br>
<video src="../../assets/2.mp4" controls="controls"></video>
<!-- 通过 为 transition-group 元素,设置 tag 属性,指定 transition-group 渲染为指定的元素,如果不指定 tag 属性,默认,渲染为 span 标签 -->
<div class="bar">
<transition-group appear tag="div">
<div class="divbar" v-bind:style="{marginTop:item.height}" v-for="(item,i) in list" :key="item.id">
{{item.id}}
</div>
</transition-group>
</div>
</div>
</template>
<script>
import axios from 'axios'
//判断当前浏览器是否支持WebSocket
export default {
data(){
return{
id: '',
ah: '0px',
name: '',
message: '',
list: [
]
}
},
methods: {
//获取随机下标
randomIndex: function () {
return Math.floor(Math.random() * this.list.length);
},
//增加数据(需要修改集成)
add: function () {
//后端的ip地址
let url2 = 'http://192.168.9.74:8092/exercise-server/checkCenter/socket/push/21?message='+this.id+'';
axios.get(url2)
// 获取成功
.then(function (response) {
console.log("发送弹幕成功");
})
// 获取失败
.catch(function(error) {
window.alert("失败");
});
},
//弹幕验证
getPass(msg){
if(msg.length > 20){
return false;
}
return true;
},
//websocket
getcon(){
let socket;
let that=this;
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else {
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
socket = new WebSocket('ws://192.168.9.74:8092/exercise-server/checkCenter/socket/21');
/*socket = new WebSocket("${basePath}websocket/${cid}".replace("http","ws"));*/
//打开事件
socket.onopen = function () {
console.log('Socket 已打开');
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function (msg) {
console.log(msg.data);
//发现消息进入 开始处理前端触发逻辑
that.message = msg.data;
if(that.getPass(that.message)){
let h=Math.floor(Math.random() * (10 - 5 + 1) + 5) * 20 + 'px';
that.list.splice(that.randomIndex(), 0, {id: that.message, height: h });
that.id = that.name = '';
}
};
//关闭事件
socket.onclose = function () {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function () {
alert("Socket发生了错误");
//此时可以尝试刷新页面
}
}
}
},
mounted: function(){
this.getcon();
},
watch: {
//监听数据变化
'list': function(){
if(this.list.length > 25){
this.list.splice(2,1);
}
}
}
}
</script>
<style scoped>
#test{
position: relative;
}
.bar{
position: absolute;
margin-top:-500px;
}
.divbar{
margin-left: -200px;
color: white;
position: absolute;
font-size: 20px;
border:none;
margin-top: 15px;
background: none;
width:70px;
}
.v-leave-active{
animation: v 10s reverse;
}
.v-enter-active{
animation: v-in 20s;
}
@keyframes v-in {
0% {
transform: translateX(1800px);
}
100% {
transform: translateX(270px);
}
}
</style>
后端代码
原理:利用websocket即时通信
代码:
1.开启websocket
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
2.websocket实现层
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import lombok.extern.slf4j.Slf4j;
//控制层的路由可根据自身的情况修改
@ServerEndpoint("/exercise-server/checkCenter/socket/{sid}")
@Component
public class WebSocketServer {
static Log log=LogFactory.get(WebSocketServer.class);
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//接收sid
private String sid="";
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session,@PathParam("sid") String sid) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
this.sid=sid;
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到来自窗口"+sid+"的信息:"+message);
//群发消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群发自定义消息
* */
public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
log.info("推送消息到窗口"+sid+",推送内容:"+message);
for (WebSocketServer item : webSocketSet) {
try {
//这里可以设定只推送给这个sid的,为null则全部推送
if(sid==null) {
item.sendMessage(message);
}else if(item.sid.equals(sid)){
item.sendMessage(message);
}
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
3.控制层
import com.kedacom.ctsp.web.controller.message.ResponseMessage;
import com.kedacom.exercise.exercise.service.websocket.WebSocketServer;
import com.kedacom.kidp.base.web.controller.BaseCrudController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
@RestController
@RequestMapping("/checkCenter")
public class CheckCenterController{
//页面请求
@GetMapping("/socket/{cid}")
public String socket(@PathVariable String cid) {
return "success";
}
@RequestMapping("/socket/push/{cid}")
public String pushToWeb(@PathVariable String cid,String message) {
try {
WebSocketServer.sendInfo(message,cid);
} catch (IOException e) {
e.printStackTrace();
return "error";
}
return "success";
}
}
总结
-
vue分css过渡和css动画,要根据不同情况选择不同类型(CSS 动画用法同 CSS 过渡,区别是在动画中 v-enter 类名在节点插入 DOM 后不会立即删除,而是在 animationend 事件触发时删除。)
-
v-enter:定义进入过渡的开始状态。在元素被插入之前生效,在元素被插入之后的下一帧移除。
-
v-enter-active:定义进入过渡生效时的状态。在整个进入过渡的阶段中应用,在元素被插入之前生效,在过渡/动画完成之后移除。这个类可以被用来定义进入过渡的过程时间,延迟和曲线函数。
-
v-enter-to: 2.1.8版及以上 定义进入过渡的结束状态。在元素被插入之后下一帧生效 (与此同时 v-enter 被移除),在过渡/动画完成之后移除。
-
v-leave: 定义离开过渡的开始状态。在离开过渡被触发时立刻生效,下一帧被移除。
-
v-leave-active:定义离开过渡生效时的状态。在整个离开过渡的阶段中应用,在离开过渡被触发时立刻生效,在过渡/动画完成之后移除。这个类可以被用来定义离开过渡的过程时间,延迟和曲线函数。
-
v-leave-to: 2.1.8版及以上 定义离开过渡的结束状态。在离开过渡被触发之后下一帧生效 (与此同时 v-leave 被删除),在过渡/动画完成之后移除。
-
websockte是一个协议和http一样