您现在的位置是:首页 > 网站制作 > vue.js心得vue.js心得
Vue Websocket 长连接
蒙xs2022-03-18【vue.js心得】人已围观
简介即时通话,长连接
<template>
<div>
11
</div>
</template>
<script>
export default {
name: "Resource",
data() {
return {
wsUrl: "",
websocket: null
};
},
methods: {
updateUrl(urlPath) {
let _this = this;
if (urlPath.indexOf("sockjs") != -1) {
_this.wsUrl =
"http://" +
'www.baidu.com' +//链接地址
urlPath +
";" +
'_this.userData.user';
} else {
if (window.location.protocol == "http:") {
_this.wsUrl =
"ws://" +
'www.baidu.com' +//链接地址
urlPath +
";" +
'_this.userData.user';
} else {
_this.wsUrl =
"wss://" +
'www.baidu.com' +//链接地址
urlPath +
";" +
'_this.userData.user';//登录用户的用户名
}
}
},
webSocketLink() {
let _this = this;
var heartCheck = {
timeout: 5000,
timeoutObj: null,
reset: function () {
clearInterval(this.timeoutObj);
return this;
},
start: function () {
this.timeoutObj = setInterval(function () {
_this.websocket.send("HeartBeat");
console.log("HeartBeat");
}, this.timeout);
},
};
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);
}
_this.websocket.onopen = function () {
console.log("websock连接成功");
heartCheck.reset().start();
};
_this.websocket.onmessage = function (event) {
console.log(event.data);
};
},
},
beforeRouteLeave(to, from, next) {
if (this.websocket) {
this.websocket.close();
}
},
created() {
this.webSocketLink();
},
};
</script>
Tags:
很赞哦! ()
上一篇:Form Data提交数据
下一篇:获取当前url信息