前言:
项目中因为有的数据使用分页后数据加载还是很慢,所以考虑使用websocket来解决。后端获取到数据库数据后就依次返回给前端,这样就不需要等分页数据全部获取后才返回。
websocket封装请看我的另一篇博文:(这个扩展性和可维护性好一些)
封装websocket请求-----vue项目实战(完整版)
1、需求概述
点击按钮后才开启websocket连接,然后发送数据给后端(相当于post请求中也是需要传递数据给后端使用),在websocket实例对象的onmessage 函数中能获取到后端返回的数据进行处理渲染。
2、代码
export default {
data() {
return {
websock: null
}
},
destroyed () {
if(this.websock){
this.websock.close()
}
},
methods: {
initWebSocket(){
if(typeof(WebSocket) === "undefined"){
alert("您的浏览器不支持WebSocket")
return false
}
const wsuri = 'ws://*.*.*.*:8081/dns-monitor'
this.websock = new WebSocket(wsuri)
this.websock.onopen = this.websocketonopen
this.websock.onmessage = this.websocketonmessage
this.websock.onerror = this.websocketonerror
this.websock.onclose = this.websocketclose
},
websocketonopen(){
console.log('WebSocket连接成功')
},
websocketonmessage(e){
let dataJson = JSON.parse(e.data)
console.log(dataJson)
},
websocketonerror(e){
console.log(`连接失败的信息:`, e)
this.initWebSocket()
},
websocketclose(e){
console.log('断开连接',e)
},
btnClick () {
if(this.websock){
this.websock.close()
}
this.initWebSocket()
setTimeout( () => {
if (this.websock.readyState === 1) {
let obj = {
jobId: 111,
token: 'xxxxx',
message: 'send ok'
}
this.websock.send(JSON.stringify(obj))
}
}, 500)
}
}
}
websocket接口数据接收示意图:
3、websocket的几个状态
websocket的几个状态。通常在实例化一个websocket对象之后,客户端就会与服务器进行连接。但是连接的状态是不确定的,于是用readyState属性来进行标识。它有四个值,分别对应不同的状态:
CONNECTING:值为0,表示正在连接;
OPEN:值为1,表示连接成功,可以通信了;
CLOSING:值为2,表示连接正在关闭;
CLOSED:值为3,表示连接已经关闭,或者打开连接失败。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)