不同手机,实现同步更新(websockets)

该段代码展示了如何根据不同的域名环境配置WebSocket连接,并处理连接的开闭、错误及消息接收。在WebSocket连接成功后,进行了心跳检测的重置。当连接关闭或出现错误时,实现了重连机制。此外,还定义了数据接收后的处理方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



data() {
    return {
        websock: null,
    }
}

methods:{
     // websockets
    initWebSocket() {
      
      let httpdemo = window.location.hostname;
      const urlHeader = window.location.protocol + "//";
      var base = "";
      if (  
        httpdemo === "testmqgitfrontend.meequ.cn" ||
        httpdemo === "localhost" ||
        httpdemo === "192.168.1.136"
      ) {   
        base = "ws://120.25.2.34:10125";    //判断在测试环境下的域名
      } else {
        base = "wss://mqfrontend.mizhuanbao.cn:10125";  //判断在正式环境下的域名
      }
      var url = base + actId 
      // WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
      // console.log("调用了链接websock  ,获取的用户id为   :"+store.getters.userInfo.id)
      // console.log(url);
      this.websock = new WebSocket(url);
      this.websock.onopen = this.websocketOnopen;
      this.websock.onerror = this.websocketOnerror;
      this.websock.onmessage = this.websocketOnmessage;
      this.websock.onclose = this.websocketOnclose;
      console.log("Socket", this.websock);
    },
    websocketOnopen() {
      console.log("WebSocket连接成功");
      //心跳检测重置
      // this.heartCheck.reset().start();
    },
    websocketOnerror(e) {
      console.log("WebSocket连接发生错误");
      this.reconnect();
    },
    //调用后台数据
    websocketOnmessage(e) {
      console.log("监听关闭" + e);
      console.log("-----接收消息-------", e.data);
      this.baseData();
      var data = eval("(" + e.data + ")"); //解析对象
    },
    websocketOnclose(e) {
      console.log("connection closed (" + e.code + ")");
      this.reconnect();
    },
    websocketSend(text) {
      // 数据发送
      try {
        this.websock.send(text);
      } catch (err) {
        console.log("send failed (" + err.code + ")");
      }
    },
    reconnect() {
      var that = this;
      if (that.lockReconnect) return;
      that.lockReconnect = true;
      //没连接上会一直重连,设置延迟避免请求过多
      setTimeout(function () {
        console.info("尝试重连...");
        that.initWebSocket();
        that.lockReconnect = false;
      }, 5000);
    },

}
 created() {
    this.initWebSocket();
    
    
  },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值