WebSocket 使用

WebSocket 提供了一种双向通信机制,可以在客户端和服务器之间建立持久性连接,实现实时的数据传输。在前端,你可以使用 JavaScript 中的 WebSocket API 来创建 WebSocket 连接,并监听来自服务器的消息事件。一旦建立了连接,服务器就可以随时向客户端发送消息,而不需要客户端发起请求。

  data() {
    return {
      websock: null, //建立的连接
      lockReconnect: false, //是否真正建立连接
      timeout: 59 * 1000, //30秒一次心跳
      timeoutObj: null, //心跳心跳倒计时
      serverTimeoutObj: null, //心跳倒计时
      timeoutnum: null, //断开 重连倒计时
    };
  },
  mounted() {
    this.initWebSocket();
  },
  beforeDestroy() {
    //WebSocket 连接关闭时要执行的操作
    this.websock.onclose = this.websocketclose;
    //立即关闭连接
    this.websock.close();
  },
  methods: {

     /**
     * 创建websocket
     */
    initWebSocket() {
      // XXXXX 连接地址
      this.websock = new WebSocket("XXXXXXXXXX");
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onerror = this.websocketonerror;
      this.websock.onopen = this.websocketonopen;
      this.websock.onclose = this.websocketclose;
    },
    reconnect() {
      //重新连接
      var that = this;
      if (that.lockReconnect) {
        return;
      }
      that.lockReconnect = true;
      //没连接上会一直重连,设置延迟避免请求过多
      that.timeoutnum && clearTimeout(that.timeoutnum);
      that.timeoutnum = setTimeout(function () {
        //新连接
        that.initWebSocket();
        that.lockReconnect = 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(function () {
        //这里发送一个心跳,后端收到后,返回一个心跳消息,
        if (self.websock.readyState == 1) {
         
          //如果连接正常
          self.websock.send("heartbeat");
        } else {
      
          //否则重连
          self.reconnect();
        }
        self.serverTimeoutObj = setTimeout(function () {
          //超时关闭
       
          self.websock.close();
        }, self.timeout);
      }, self.timeout);
    },

    // 连接建立之后执行send方法发送数据
    websocketonopen() {
  
      let data = {
        code: 0,
        msg: "这是client:初次连接",
      };
      //开启心跳
      this.start();
      // this.websocketsend(data);
    },
    websocketonerror() {
      console.log("WebSocket连接失败");
      this.reconnect();
    },
    // 数据接收
    websocketonmessage(e) {
      // e.data 可以是一个文本、JSON、HTML
      console.log("WebSocket接收数据", e.data);

      //收到服务器信息,心跳重置
      this.reset();
    },
    // 数据发送
    websocketsend(Data) {
      this.websock.send(Data);
    },
    // 关闭
    websocketclose(e) {
      // console.log("已关闭连接", e);
      this.reconnect();
    },
  }

注意:

虽然 WebSocket 是一种双向通信协议,但在某些情况下,网络设备、代理服务器或防火墙可能会限制连接的空闲时间或导致连接超时。这些限制可能导致 WebSocket 连接在长时间没有数据交换时被中断或关闭。设置心跳机制可以解决这个问题。当 WebSocket 连接打开时,会启动一个定时器,定期发送一个字符串 'heartbeat' 给服务器

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值