h5 websocket 断开重新连接

时间:2024-03-12 18:46:53

最近的项目中使用ws 长连接来接收和发送消息, 直接上代码

import * as SockJS from "sockjs-client";
import Stomp from "stompjs";

  

connection() {
      if (this.clientSubscribe) {
        console.log(\'unsubscribe\')
        this.clientSubscribe.unsubscribe()
      }
      const token = "";
      // const TENANT_ID = getStore({name: \'tenantId\'}) ? getStore({name: \'tenantId\'}) : \'1\'
      const headers = {
        Authorization: "Bearer " + token,
        chatSessionId: this.chatBaseInfo.chatSessionId,
        tempToken: this.chatBaseInfo.tempToken,
      };
      // 建立连接对象
      this.socket = new SockJS("/bot/ws"); // 连接服务端提供的通信接口,连接以后才可以订阅广播消息和个人消息
      //获取STOMP子协议的客户端对象
      this.stompClient = Stomp.over(this.socket);
      //this.stompClient.debug = true
      //向服务器发起websocket连接
      this.stompClient.connect(
        headers,
        () => {
          this.isConnection = false
          this.successCallback()
        },
        () => {
          console.log(\'断开重新连接\')
          this.isConnection = true
          console.log( this.stompClient)
          if (this.env === "WEB") {
            setTimeout(() => {
              this.connection()
            },2000)
          }
          
          //this.reconnect(this.successCallback);
        }
      );
    },

  

successCallback(){
      
      this.clientSubscribe = this.stompClient.subscribe(
            "/x99/receive/" + this.chatBaseInfo.chatSessionId,
            (msg) => {
              // 订阅服务端提供的某个topic;
              // 处理接收的数据
              
            }
          );
    },

  遇到的问题是  在ios手机端 锁屏的情况下 会把websocket 断开   解决的方案是

mounted() {
    
    document.addEventListener(\'visibilitychange\', () => {

      if (!document.hidden) {//页面呼出

        if (this.stompClient&&!this.stompClient.connected) {

          this.connection()
        }
      }
    })
  },

  注意  1.在web 端是没有这个事件的  所以在重新连接的地方加了判断 是web 端用了定时器去冲新连接

    2.在重新连接前需要判断之前的订阅是不是存在  存在的话先取消订阅,

  if (this.clientSubscribe) {
          this.clientSubscribe.unsubscribe()
       }