微信小程序socket连接和断线重连

可以在app.js中全局使用也可以在首页使用

let socketServer // 全局socket连接实例
let timer // 全局定时器

Page({
  data: {
   
  },
  /** 首次加载*/
  onLoad(options) {
    // 判断socket不是在连接中或者已经连接成功就去连接
    if (![0, 1].includes(socketServer?.readyState)) {
      // 连接socket服务
      this.connectedWebSocket()
    }
  },
  /** 发送心跳*/
  socketSend() {
    timer = setInterval(() => {
      let message = JSON.stringify({
        messageType: 'HEARTBEAT'
      })
      setTimeout(() => {
        socketServer.send({
          data: message,
          success: () => {
            console.log('发送成功');
          },
          fail: () => {
            console.log('发送失败');
            // 发送失败判断没有连接成功就需要调用重连
            if (socketServer.readyState !== 1) {
              this.connectedWebSocket()
            }
          },
          complete: () => {
            console.log(socketServer);
          }
        })
      }, 0)
    }, 1000 * 25);
  },
  /** 监听socket信息*/
  onSocketMessage(info) {
    let data = JSON.parse(info.data)
    console.log('SOCKET接收的信息', data);
    // 审核通知
    if (data.messageType == 'CHECK_NOTICE') {
      。。。。。
      // 公告
    } else if (data.messageType == 'NOTICE') {
      。。。。。
      // 字典更新
    } else if (data.messageType == 'CACHE') {
     。。。。
    } else if (data.messageType == 'CONTRACT_ALERT') {
      。。。。
    }
  },

  /** 连接soket服务 */
  connectedWebSocket() {
    const token = wx.getStorageSync('token')
    const currentId = wx.getStorageSync('currentId')
    socketServer = wx.connectSocket({
      url: http.SOCKET_URL,
      header: {
        'content-type': 'application/json',
        token,
        currentId,
      },
      success: (info) => {
        console.log('soket服务连接成功', info);
        // 连接成功清除定时器然后发送心跳
        clearInterval(timer);
        this.socketSend()
      },
      fail: (err) => {
        console.log('soket服务连接失败', err);
      },
    })
    // 监听返回消息
    socketServer.onMessage(this.onSocketMessage)
    console.log('socket实例', socketServer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 监听页面卸载然后关闭连接理论上好像没问题但是也似乎没成功过
    clearInterval(timer);
    socketServer.close({
      success: () => {
        console.log('服务关闭成功');
      },
      fail: (err) => {
        console.log('服务关闭失败', err);
      }
    })
  },
})
posted @ 2022-05-10 14:43  大海&  阅读(2162)  评论(1编辑  收藏  举报