websocket心跳监测和重连机制

data(){
	return {
	  timeout: 28*1000,//30秒一次心跳
      timeoutObj: null,//心跳心跳倒计时
      serverTimeoutObj: null,//心跳倒计时
      timeoutnum: null,//断开 重连倒计时
      surpriseNums: null,
      surpriseReconnect: false,//是否真正建立连接
	}
},
mounted(){
	this.surpriseNum();
},
methods: {
	surpriseNum() {
	   var _this = this;
	   if (!window.location.origin) {
	     window.location.host =
	       window.location.hostname +
	       (window.location.port ? ":" + window.location.port : "");
	   }
	
	   var protocol = "ws";
	   if (location.protocol === "https:") {
	     protocol = "wss";
	   }
	
	   _this.surpriseNums = new WebSocket(
	     `${protocol}://${window.location.host}/api/chatroom/room/` +
	             _this.chatRoomId +
	             "/type/image" +
	             "/member_id/" +
	             _this.userInfo.id +
	             "/member_name/" +
	             _this.userInfo.name
	   );
	 
	   _this.surpriseNums.onopen = function(evt) {
	     console.log("surpriseNum建立连接");
	     //开启心跳
	    _this.start();
	   };
	   _this.surpriseNums.onclose = function(evt) {
	     console.log("surpriseNum关闭连接");
	     //重连
	     _this.reconnect();
	   };
	   _this.surpriseNums.onerror = function(evt) {
	     //重连
	     _this.reconnect();
	   };
	   _this.surpriseNums.onmessage = function(evt) {
	     //收到服务器信息,心跳重置
	     _this.reset();
	   };
	 },
	reconnect() {//重新连接
	  var that = this;
	  if(that.surpriseReconnect) {
	    return;
	  };
	  that.surpriseReconnect = true;
	  //没连接上会一直重连,设置延迟避免请求过多
	  that.timeoutnum && clearTimeout(that.timeoutnum);
	  that.timeoutnum = setTimeout(function () {
	    //新连接
	    that.surpriseNum();
	    that.surpriseReconnect = false;
	  },5000);
	},
	reset(){//重置心跳
	  var that = this;
	  //清除时间
	  clearTimeout(that.timeoutObj);
	  clearTimeout(that.serverTimeoutObj);
	  //重启心跳
	  that.start();
	},
	start(){//开启心跳
	  var self = this;
	  self.timeoutObj && clearTimeout(self.timeoutObj);
	  self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
	  self.timeoutObj = setTimeout(() => {
	      //这里发送一个心跳,后端收到后,返回一个心跳消息,
	      if (self.surpriseNums.readyState == 1) {//如果连接正常
	      var data = {
	        action: "hert",
	        content: {
	          type: "words",
	          content: '', //如果type是words,表示发送文字;如果type是image,标识图片的缩略图,并且org_iamge是原图
	          org_image: ""
	        }
	      };
	          self.surpriseNums.send(JSON.stringify(data));
	      }else{//否则重连
	          self.reconnect();
	      }
	      self.serverTimeoutObj = setTimeout(function() {
	          //超时关闭
	          self.surpriseNums.close();
	      }, self.timeout);
	
	  }, self.timeout)
	},
}