vue使用websocket连接优化性能方式
作者:跳跳的小古风
这篇文章主要介绍了vue使用websocket连接优化性能方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
使用websocket连接优化性能
需求
前端做echarts 图表展示,每隔五秒钟刷新一次数据
问题
前期用的是axios 轮询,添加定时器每秒请求一次接口,出现卡顿,服务器负担大现象,且不同人打开可能会显示不同的数据
解决
使用了websocket建立长连接
(websocket只需要一次HTTP握手,所以说整个通讯过程是建立在一次连接/状态中,也就避免了HTTP的非状态性,服务端会一直知道你的信息,直到你关闭请求)
data(){
WsUrl:'',//网址
lock:false//重复链接标识
url:'',
token:'',
deviceid:'',
reconnetTimeout:null,
timer:null,
serverTimer:null,
timeout:10*1000
}
mounted () {
this.createWebsocket()
},
methods:{
createWebsocket(){
try{
initWebSocket()
}catch{
reConnect()
}
}
initWebSocket () {
// 创建一个构造函数返回一个websocket对象
this.wsurl = `ws://${this.url}${this.types}${this.token}?deviceid=${this.deviceid}`
this.websock = new WebSocket(wsurl)
// 接受到信息后的回调函数
this.websock.onmessage = this.websocketonmessage
// 连接成功后的回调函数
this.websock.onopen = this.websocketonopen
// 连接失败后的回调函数
this.websock.onerror = this.websocketonerror
// 用于指定关闭后的回调函数
this.websock.onclose = this.websocketclose
},
// 连接建立失败重连
websocketonerror () {
this.reConnet()
},
websocketonopen(){
this.start(this.websocket)
this.websocketSend()
}
// 数据接收
websocketonmessage (e) {
// 处理业务逻辑
if(e.data==‘pong'){
this.statr(this.websock)
}
}
// 关闭
websocketclose (e) {
this.reConnet()
},
}
reConnect() {
if(this.lock) {
return;
};
this.lock = true;
//没连接上会一直重连,设置延迟避免请求过多
this.reconnectTime&& clearTimeout(this.reconnectTime);
this.reconnectTime= setTimeout(function () {
this.createWebSocket();
this.lock = false;
}, 4000);
}
WebsocketSend(){
this.websock.send(‘ping')
}
start(ws){
this.serverTimer&&clearTimeout(this.serverTime)
this.timer&&clearTimeout(this.timer)
this.timer=setTimeout(()=>{
ws.send(‘ping')
this.serverTimer=setTimeout(()=>{
ws.close()
},this.timeout};
},this.timeout)
}
websocket在vue上的使用
<template>
<div>
<button @click="send">发消息</button>
</div>
</template>
<script>
export default {
data () {
return {
path:"ws://192.168.1.145:8080",
socket:""
}
},
mounted () {
// 初始化
this.init()
},
methods: {
init: function () {
if(typeof(WebSocket) === "undefined"){
alert("您的浏览器不支持socket")
}else{
// 实例化socket
this.socket = new WebSocket(this.path)
// 监听socket连接
this.socket.onopen = this.open
// 监听socket错误信息
this.socket.onerror = this.error
// 监听socket消息
this.socket.onmessage = this.getMessage
}
},
open: function (res) {
console.log("socket连接成功")
},
error: function () {
console.log("连接错误")
},
getMessage: function (msg) {
/*数据*/
console.log(msg.data)
},
/* send: function () {
this.socket.send(params)
},*/
close: function () {
console.log("socket已经关闭")
}
},
destroyed () {
// 销毁监听
this.socket.onclose = this.close
}
}
</script>
<style>
</style>总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
