zoukankan      html  css  js  c++  java
  • h5 websocket 断开重新连接

    最近的项目中使用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()
           }
  • 相关阅读:
    分享一下我珍藏的各种资料。
    JEditorPane中html文档中文乱码解决
    ubuntu恢复rm -rf误删文件
    MBR与分区表备份与恢复
    ubuntu tab命令补全失效
    selinux理解1-selinux介绍
    Mac-Xcode统计整个项目代码行数
    Mac清理空间-Xcode-删除相关文件
    # iOS开发
    Charles问题总结-最新版4.5.6
  • 原文地址:https://www.cnblogs.com/buxiugangzi/p/13678286.html
Copyright © 2011-2022 走看看