vue中使用WebSocket方法

websocket使用

1.创建对象
2.监听连接事件
3.监听数据接收事件
4.发送数据
在app.js中添加如下代码:

init: function () {
      let that = this;
      if (typeof WebSocket === "undefined") {
        	alert("您的浏览器不支持socket")
      } else {
        // 实例化socket
        that.ws = new WebSocket('ws://xxxxx');
        that.global.setWs(that.ws);
        that.ws.onopen = function () {
          console.log("连接成功");
          that.start();
        };
        // 监听socket消息
        that.ws.onmessage = (msg) => {
          const h = this.$createElement;
          /*socket消息 */
          that.reset();
        };
        //连接错误
        that.ws.onerror = function () {
          console.log("WebSocket连接发生错误");
          //重连
          if (that.title == "token为空") {
            that.global.ws.close();
          } else {
            that.reconnect();
          }
        };
        that.ws.onclose = function () {
          // 关闭 websocket
          console.log("连接已关闭....");
          that.global.ws.close();
          //断线重新连接
          //   setTimeout(() => {
          //     that.init();
          //   }, 2000);
        };
      }
    },
     //重新连接
    reconnect() {
      let that = this;
      if (that.global.ws && that.global.ws.readyState == 1) {
        clearInterval(that.timeoutnum);
        that.timeoutnum = null;
        that.timeNum = 0;
        return;
      }
      if (!that.timeoutnum) {
        that.timeoutnum = setInterval(function () {
          if (that.global.ws && that.global.ws.readyState == 1) {
            clearInterval(that.timeoutnum);
            that.timeoutnum = null;
            that.timeNum = 0;
            return;
          }
          //新连接
          that.init();
          that.timeNum++;
          if (that.timeNum >= 3) {
            clearInterval(that.timeoutnum);
            that.timeoutnum = null;
            that.timeNum = 0;
          }
        }, 1000);
      }
    },
    //重置心跳
    reset() {
      //清除时间
      clearTimeout(this.timeoutObj);
      clearTimeout(this.serverTimeoutObj);
      //重启心跳
      this.start();
    },
	//开启心跳
    start() {
      let that = this;
      let date = new Date();
      that.timeoutObj && clearTimeout(that.timeoutObj);
      that.serverTimeoutObj && clearTimeout(that.serverTimeoutObj);
      that.timeoutObj = setTimeout(function () {
        //这里发送一个心跳,后端收到后,返回一个心跳消息,
        if (that.global.ws && that.global.ws.readyState == 1) {
          //如果连接正常
          that.global.ws.send(`发送心跳给后端${date}`);
        } else {
          //否则重连
          that.reconnect();
        }
      }, that.timeout);
    },

你可能感兴趣的:(websocket,vue.js,javascript)