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);
    },
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值