data()
{
return{
websockets:""
}
},
methods:{
//3.建立websockets连接数据
initWebSockets() {
if (typeof WebSocket === "undefined") {
return false;
}
let wsuri;
// websocket地址
wsuri = 'ws://-------------------';
// console.log('传送的ws是:',wsuri)
this.websockets = new WebSocket(wsuri);
this.websockets.onopen = this.websocketonopens;
this.websockets.onmessage = this.websocketonmessages;
this.websockets.onerror = this.websocketonerrors;
this.websockets.onclose = this.websocketcloses;
},
//连接成功
websocketonopens() {
console.log("WebSocket连接成功");
// let token = JSON.parse(sessionStorage.getItem('token'))
// let actions = {
// "token": token,
// };
// if (this.websockets.readyState === 1) {
// this.websockets.send(JSON.stringify(actions))
// }
// console.log('JSON.stringify(actions)',JSON.stringify(actions))
// console.log('actions',actions)
// // 添加心跳检测,每30秒发一次数据,防止连接断开(这跟服务器的设置有关,如果服务器没有设置每隔多长时间不发消息断开,可以不进行心跳设置)
// let self = this;
// if (this.websockets.readyState === 1) {
// this.timerWS = setInterval(() => {
// try {
// let token = JSON.parse(sessionStorage.getItem('token'))
// let actions = {
// "token": token,
// };
// self.websockets.send(JSON.stringify(actions));
// } catch (err) {
// console.log('断开了:' + err);
// self.connection()
// }
// }, 30000)
// }
},
//接收后端返回的数据,可以根据需要进行处理
websocketonmessages(e) {
let data1Json = JSON.parse(e.data);
new Promise((resolve) => {
setTimeout(() => {
setTimeout(() => {
if (data1Json.id) {
//数据处理
}
}, 40)
resolve()
}, 40)
}).then(() => {
return new Promise((resolve) => {
resolve()
})
})
},
//连接建立失败重连
websocketonerrors(e) {
console.log(`连接失败的信息:`, e);
this.initWebSockets(); // 连接失败后尝试重新连接
},
//关闭连接
websocketcloses(e) {
console.log("断开连接", e);
}
},
destroyed(){
if(this.websockets){
this.websockets.close()
}
}
websocket复制使用
最新推荐文章于 2021-12-14 09:32:04 发布