socket

该博客详细描述了一个WebSocket连接的管理过程,包括连接建立、错误处理、断开后的重连策略。当连接错误时,会进行重连尝试,并限制了重试次数。在达到最大重试次数后,系统将提示TCP连接超时。此外,还提供了初始化连接和关闭连接的处理逻辑。
 socket: null,
 lockReconnect: false,
 tt: "",
reconnect(service) {
      this.tt && clearTimeout(this.tt);
      if (this.limitConnect > 0) {
        if (localStorage.getItem("lockReconnect") != true) {
          localStorage.setItem("lockReconnect", 1);
          this.limitConnect--;
          this.timeConnect++;
          console.log("第" + this.timeConnect + "次重连");
          // 进行重连
          this.tt = setTimeout(() => {
            this.init(service);
            localStorage.removeItem("lockReconnect");
          }, 2000);
        }
      } else {
        console.log("TCP连接已超时");
      }
    },

    init(url) {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        this.socket = new WebSocket(url);
        this.socket.onopen = this.open;
        this.socket.onerror = this.error;
        this.socket.onmessage = this.getMessage;
      }
    },
    open() {
      console.log("socket连接成功");
    },
    error(e) {
      console.log(e);
      console.log("连接错误");
      if (this.socket.readyState == 3) {
        this.init(screenws);
      }
      this.reconnect(screenws);
    },
    getMessage(msg) {
      console.log(msg, "返回的值");
    },
    close(e) {
      console.log(e);
      console.log("socket已经关闭");
      this.reconnect(screenws);
    },
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值