WebSocket 心跳检测&&重新连接

	//初始化websocket
			createWebSocket()
			function createWebSocket() {
				try {
					if ('WebSocket' in window) {
						websocket = new WebSocket("wss://xxx");
					}
					init()
				} catch (e) {
					console.log('catch' + e);
					reconnect();
				}
			}
			
			function init() {
				websocket.onopen = function() {
					websocket.send('参数')
					heartCheck.reset().start();
				};
				websocket.onmessage = function(event) {
					console.log("WebSocket:收到一条消息", event);
					heartCheck.reset().start();
				};
				//连接发生错误的回调方法
				websocket.onerror = function(event) {
					console.log("WebSocket:发生错误");
					reconnect();
				};
				//连接关闭的回调方法
				websocket.onclose = function(event) {
					console.log("WebSocket:已关闭");
					heartCheck.reset(); //心跳检测
					reconnect();
				};
			
				//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
				window.onbeforeunload = function() {
					websocket.close();
				};
			
				//关闭连接
				function closeWebSocket() {
					websocket.close();
				}
			
				//发送消息
				function send(message) {
					websocket.send(message);
				}
			}
			//心跳
			var lockReconnect = false,
				tt;
			/**
			 * websocket重连
			 */
			function reconnect() {
				if (lockReconnect) {
					return;
				}
				lockReconnect = true;
				tt && clearTimeout(tt);
				tt = setTimeout(function() {
					console.log('重连中...');
					lockReconnect = false;
					createWebSocket();
				}, 4000);
			}
			/**
			 * websocket心跳检测
			 */
			var heartCheck = {
				timeout: 5000,
				timeoutObj: null,
				serverTimeoutObj: null,
				reset: function() {
					clearTimeout(this.timeoutObj);
					clearTimeout(this.serverTimeoutObj);
					return this;
				},
				start: function() {
					var self = this;
					this.timeoutObj && clearTimeout(this.timeoutObj);
					this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
					this.timeoutObj = setTimeout(function() {
						//这里发送一个心跳,后端收到后,返回一个心跳消息,
						//onmessage拿到返回的心跳就说明连接正常
						let message = {
							header: {
								method: "heartbeat",
							}
						};
						websocket.send(JSON.stringify(message));
						self.serverTimeoutObj = setTimeout(function() { // 如果超过一定时间还没重置,说明后端主动断开了
							console.log('关闭服务');
							websocket.close(); //如果onclose会执行reconnect,我们执行 websocket.close()就行了.如果直接执行 reconnect 会触发onclose导致重连两次
						}, 3000)
					}, 5000)
				}
			};
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值