关于webSocket建⽴前后端连接,并进⾏⼼跳机制的实现最近在做⼀个后台实时通知的项⽬,项⽬中⽤到了socket来实现前后端建⽴通信,在此记录⼀下。
<template>
<div>
<h1>测试webSocket</h1>
<div id ="aaa" ></div>
</div>
</template>
<script>
var that;
export default {
data(){
return {
data:0,
timeout: 30 * 1000,//30秒⼀次⼼跳
timeoutObj: null,//⼼跳⼼跳倒计时
serverTimeoutObj: null,//⼼跳倒计时
timeoutnum: null,//断开重连倒计时
websocket: null,
}
},
created() { // 页⾯创建⽣命周期函数
that = this;
that.initWebSocket()
},
destroyed: function () { // 离开页⾯⽣命周期函数
that.websocketclose();
},
methods: {
initWebSocket: function () {
// WebSocket与普通的请求所⽤协议有所不同,ws等同于http,wss等同于https
that.websocket = new WebSocket("wss://127.0.0.1:9231/kh_snmptrap/websocket/lsmsp");
pen = that.websocketonopen;
r = that.websocketonerror;
ssage = that.setOnmessageMessage;
lose = that.websocketclose;
// 监听窗⼝关闭事件,当窗⼝关闭时,主动去关闭websocket连接,防⽌连接还没断开就关闭窗⼝,server端会抛异常。
// beforeunload = beforeunload
},
reconnect: function () { // 重新连接
if(that.lockReconnect) return;
that.lockReconnect = true;
//没连接上会⼀直重连,设置延迟避免请求过多
that.timeoutnum && clearTimeout(that.timeoutnum);
that.timeoutnum = setTimeout(() => {
//新连接
that.initWebSocket();
that.lockReconnect = false;
}, 5000);
},
reset: function () { // 重置⼼跳
// 清除时间
clearTimeout(that.timeoutObj);
clearTimeout(that.serverTimeoutObj);
// 重启⼼跳
that.start();
},
start: function () { // 开启⼼跳
that.timeoutObj && clearTimeout(that.timeoutObj);
that.serverTimeoutObj && clearTimeout(that.serverTimeoutObj);
that.timeoutObj = setTimeout(() => {
// 这⾥发送⼀个⼼跳,后端收到后,返回⼀个⼼跳消息,
// 这⾥发送⼀个⼼跳,后端收到后,返回⼀个⼼跳消息,
if (that.websocket && adyState == 1) { // 如果连接正常
that.websocketsend('heartbeat');
} else { // 否则重连
}
that.serverTimeoutObj = setTimeout(() => {
//超时关闭
that.websocket.close();
}, that.timeout);
}, that.timeout)
},
setOnmessageMessage: function(event) {
let obj = JSON.parse(event.data);
// console.log("obj",obj)
pe) {
case 'heartbeat':
//收到服务器信息,⼼跳重置
break;
case 'sendMessage':
that.data = obj.data
console.log("接收到的服务器消息:",JSON.stringify(obj.data,null,4))
}
},
websocketonopen: function () {
//开启⼼跳
that.start();
console.log("WebSocket连接成功"+new Date()+"----"+adyState);
},
websocketonerror: function (e) {
console.log("WebSocket连接发⽣错误" + e);
},
websocketonmessage: function (e) {
console.log(e.data);                // console.log(e);
},
websocketclose: function (e) {
that.websocket.close();
console.log("connection closed ");
},
websocketsend(messsage) {
that.websocket.send(messsage)
},
closeWebSocket() { // 关闭websocket
that.websocket.close()
}
}
}
websocket和socket</script>
<style >
</style>
还有⼀点,我这⾥是https的请求,如果你是http请求的话,把wss://127.0.0.1:8888改为ws://127.0.0.1:8888。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。