代码
initWebSocket: function () {
var url = "http://localhost:39010".replace("https://","wss://").replace("http://","ws://")+"/websocket/"+"1";
console.log(url);
this.websock = new WebSocket(url);
this.websock.onopen = this.websocketOnopen;
this.websock.onerror = this.websocketOnerror;
this.websock.onmessage = this.websocketOnmessage;
this.websock.onclose = this.websocketOnclose;
},
websocketOnopen: function () {
console.log("WebSocket连接成功");
},
websocketOnerror: function (e) {
console.log("WebSocket连接发生错误");
this.reconnect();
},
websocketOnmessage: function (e) {
console.log("-----接收消息-------",e.data);
var data = eval("(" + e.data + ")");
if(data.cmd == "time"){
this.time = data.data;
}else if(data.cmd == "random"){
this.uuid = data.data.uuid;
}
},
websocketOnclose: function (e) {
console.log("connection closed (" + e + ")");
if(e){
console.log("connection closed (" + e.code + ")");
}
this.reconnect();
},
websocketSend(text) {
try {
this.websock.send(text);
} catch (err) {
console.log("send failed (" + err.code + ")");
}
},
openNotification (data) {
var text = data.msgTxt;
const key = `open${Date.now()}`;
this.$notification.open({
message: '消息提醒',
placement:'bottomRight',
description: text,
key,
btn: (h)=>{
return h('a-button', {
props: {
type: 'primary',
size: 'small',
},
on: {
click: () => this.showDetail(key,data)
}
}, '查看详情')
},
});
},
reconnect() {
var that = this;
if(that.lockReconnect) return;
that.lockReconnect = true;
setTimeout(function () {
console.info("尝试重连...");
that.initWebSocket();
that.lockReconnect = false;
}, 5000);
},
heartCheckFun(){
var that = this;
that.heartCheck = {
timeout: 2000,
timeoutObj: null,
serverTimeoutObj: null,
reset: function(){
clearTimeout(this.timeoutObj);
return this;
},
start: function(){
var self = this;
this.timeoutObj = setTimeout(function(){
that.websocketSend("HeartBeat");
console.info("客户端发送心跳");
}, this.timeout)
}
}
},
getList: function(){
var that = this;
setInterval(function(){
that.websocketSend("random");
console.info("定时向服务器获取数据....");
}, 10000)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)