关于webSocket建立前后端连接,并进行心跳机制的实现

最近在做一个后台实时通知的项目,项目中用到了socket来实现前后端建立通信,在此记录一下。

<template>    
	<div>       
		<h1>测试webSocket</h1>
        <div id ="aaa" style="height: 300px; overflow-y: scroll; background: #333; color: #aaa; padding: 10px;"></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");
			that.websocket.onopen = that.websocketonopen;
			that.websocket.onerror = that.websocketonerror;
			that.websocket.onmessage = that.setOnmessageMessage;
			that.websocket.onclose = that.websocketclose;
            // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
            // window.onbeforeunload = that.onbeforeunload
        },
        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 && that.websocket.readyState == 1) { // 如果连接正常
                    that.websocketsend('heartbeat');
                } else { // 否则重连
                    that.reconnect();
                }
                that.serverTimeoutObj = setTimeout(() => {
                    //超时关闭
                    that.websocket.close();
                }, that.timeout);

            }, that.timeout)
        },
        setOnmessageMessage: function(event) {
            let obj = JSON.parse(event.data);
            // console.log("obj",obj)
            switch(obj.type) {
                case 'heartbeat':
                    //收到服务器信息,心跳重置
                    that.reset();
                    break;
                case 'sendMessage':
                    that.data = obj.data
                    console.log("接收到的服务器消息:",JSON.stringify(obj.data,null,4))
                    document.getElementById('aaa').innerHTML=JSON.stringify(obj.data,null,4)
            }
        },
		websocketonopen: function () {
            //开启心跳
            that.start();
            console.log("WebSocket连接成功!!!"+new Date()+"----"+that.websocket.readyState);
		},              
		websocketonerror: function (e) {                
			console.log("WebSocket连接发生错误" + e);              
		},              
		websocketonmessage: function (e) {                
			console.log(e.data);                // console.log(e);
            document.getElementById('aaa').innerHTML=e.data
        },
		websocketclose: function (e) {
            that.websocket.close();
            console.log("connection closed ");
		},
        websocketsend(messsage) {
            that.websocket.send(messsage)
        },
        closeWebSocket() { // 关闭websocket
            that.websocket.close()
        }
	}    
}
</script>
<style >
</style>

还有一点,我这里是https的请求,如果你是http请求的话,把wss://127.0.0.1:8888改为ws://127.0.0.1:8888。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

inticaler

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值