export default {
name: 'Resource',
data() {
return {
wsUrl: '',
websocket: null
}
},
methods: {
updateUrl(urlPath) {
let _this = this;
//注册Websocket的url 其中CONFIG.WEBSOCKET_URL为wensocket服务地址,_this.userData.user是登录用户的用户名,这样做为了保证不同用户的websocket地址的唯一性,防止消息发生混淆。
if (urlPath.indexOf('sockjs') != -1) {
_this.wsUrl = 'http://' + CONFIG.WEBSOCKET_URL + urlPath + ";" + _this.userData.user;
} else {
if (window.location.protocol == 'http:') {
_this.wsUrl = 'ws://' + CONFIG.WEBSOCKET_URL + urlPath + ";" + _this.userData.user;
} else {
_this.wsUrl = 'wss://' + CONFIG.WEBSOCKET_URL + urlPath + ";" + _this.userData.user;
}
}
},
webSocketLink() {
let _this = this;
//由于网络以及websocket自身的一些不稳定性,页面长时间打开的情况下有时会发生websocket链接的断开,为了防止这种情况,我们增加心跳检测机制
var heartCheck = {
timeout: 5000, //5秒
timeoutObj: null,
reset: function() {
clearInterval(this.timeoutObj);
return this;
},
start: function() {
this.timeoutObj = setInterval(function() {
_this.websocket.send("HeartBeat");
console.log("HeartBeat");
}, this.timeout)
}
};
//初始化WebSocket对象 为了兼容各个浏览器所以初始化的时候针对不同的浏览器初始化调用不同的方法。
if ('WebSocket' in window) {
_this.updateUrl("/webSocketServer");
_this.websocket = new WebSocket(_this.wsUrl);
} else if ('MozWebSocket' in window) {
_this.updateUrl("/webSocketServer");
_this.websocket = new MozWebSocket(_this.wsUrl);
} else {
_this.updateUrl("/sockjs/webSocketServer");
_this.websocket = new SockJS(_this.wsUrl)
}
//并且在websocket链接建立时触发该方法
_this.websocket.onopen = function() {
console.log("websock连接成功");
heartCheck.reset().start();
};
_this.websocket.onmessage = function(event) {
console.log(event.data);
}
}
},
//Vue组件中什么时候创建和销毁websocket对象 为了保证websocket对象能够及时创建,建议在vue的created的钩子函数中触发websocket的初始化,同时在beforeRouteLeave方法里关闭websocket的链接
beforeRouteLeave(to, from, next) {
if (this.websocket) {
this.websocket.close()
}
},
created() {
this.webSocketLink();
}
}
网友评论