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()
           }
  • 相关阅读:
    [翻译]跟我一起边译边学之Linux:目录
    [翻译]跟我一起边译边学之Linux:致谢 Acknowledgments
    计算机图形学资源收集01
    计算机图形学资源收集02
    计算机图形学资源收集04
    计算机图形学资源收集03
    C#二十几种设计模式事例下载(源码)
    在WinForm应用程序中嵌入WPF控件
    .net网站与Winform窗体的数据交互(JS调用Winform后台方法实现)
    C#调用rar.exe解压一个rar文件
  • 原文地址:https://www.cnblogs.com/buxiugangzi/p/13678286.html
Copyright © 2011-2022 走看看