vue 中如何使用websocket
前端和后端的交互模式最常见的就是前端发数据请求,从后端拿到数据后展示到页面中。如果前端不做操作,后端不能主动向前端推送数据,这也是http协议的缺陷。
因此,一种新的通信协议应运而生—websocket,他最大的特点就是服务端可以主动向客户端推送消息,客户端也可以主动向服务端发送消息,实现了真正的平等
项目中代码如下(在此记录一下,做个备注)
(亲测有效,也是踩过很多坑的,对代码进一步做了完善)
created() {
this.initWebSocket() // 连接websocket
}
destoryed() {
this.websock.close() // 离开路由之后断开websock
}
methods: {
/*
* 初始化websocket
*/
initWebSocket() {
if (!this.websock) {
const wsurl = '后端提供的地址'
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
} else {
console.log('websocket已连接')
}
},
/**
* 连接建立之后执行send方法发送数据
*/
websocketonopen(dialogQuery) {
this.sendPing() // 发送心跳
},
/**
* 连接失败重新连接
*/
websocketonerror() {
clearInterval(this.setIntervalWesocketPush)
this.websock.close()
this.initWebSocket() // 重连
},
/**
* 数据接收
*/
websocketonmessage(e) {
console.log(JSON.parse(e.data), '------ start --------')
},
/**
* 数据发送
*/
websocketsend(data) {
if (this.websock !== null && this.websock.readyState === 3) {
this.websock.close()
var time = setInterval(function() {
this.initWebSocket() // 重连
clearInterval(time)
}, Math.ceil(Math.random() * 5) === 0 ? 1000 : Math.ceil(Math.random() * 5) * 3000) // 随机3秒内重连
} else if (this.websock.readyState === 1) {
this.websock.send(JSON.stringify(data))
} else if (this.websock.readyState === 0) {
setTimeout(() => {
this.websock.send(JSON.stringify(data))
}, 2000)
}
},
/**
* 关闭
*/
websocketclose(e) {
clearInterval(this.setIntervalWesocketPush)
},
/**
* 发送心跳
*/
sendPing() {
this.websock.send('ping')
this.setIntervalWesocketPush = setInterval(() => {
this.websock.send('ping')
}, 60000)
},
}