webSocketInit () {
    const vm = this
    let token = ''
    let socketUrl = 'wss://websocket.test'
    // 建立 WebSocket 连接
    vm.socket = wx.connectSocket({
      url: socketUrl,
      header: {
        'content-type': 'application/json',
        'authorization': 'Bearer' + token,
        'x-wxapp-sockettype': 'ordertips'
      },
      success (res) {
        console.log('WebSocket 连接成功: ', res)
      },
      fail (err) {
        console.log('WebSocket 连接失败: ', err)
      }
    })
    // onOpen
    vm.socket.onOpen((ret) => {
      console.log('打开 WebSocket 连接')
    })
    // onMessage
    vm.socket.onMessage((ret) => {
      if (ret.data == 'pong') {
        return;
      }
      let data = JSON.parse(ret.data)
      wx.showToast({
        title: data.message,
        icon: 'none',
        duration: 3000
      })
    })
    // onError
    vm.socket.onError((err) => {
      console.log('WebSocket 连接失败:', err)
    })
    // onClose
    vm.socket.onClose((ret) => {
      console.log('断开 WebSocket 连接', ret)
    })
  },
  // send message
  send (msg) {
    const vm  = this
    vm.socket.send({
      data: msg,
      success (res) {
        console.log('WebSocket 消息发送成功', res)
      },
      fail (err) {
        console.log('WebSocket 消息发送失败', err)
      }
    })
  },
  // 心跳,由客户端发起
  ping () {
    const vm = this
    let times = 0
    // 每 10 秒钟由客户端发送一次心跳
    this.interval = setInterval(function () {
      if (vm.socket.readyState == 1) {
        vm.send('ping')
      } else if (vm.socket.readyState == 3) {
        times += 1
        // 超时重连,最多尝试 10 次
        if (times >= 10) {
          wx.showToast({
            title: 'WebSocket 连接已断开~',
            icon: 'none',
            duration: 3000
          })
          clearInterval(vm.interval)
        }
        vm.reconnect()
      }
    }, 10000)
  },
  // WebSocket 断线重连
  reconnect () {
    const vm = this
    vm.webSocketInit()
  },

标签: none

仅有一条评论

  1. liziyu liziyu

    26

添加新评论