微信小程序 实现websocket长连接 以及断开连接之后自动重连

app.js

let socketMsgQueue = []
let isLoading = false

App({
  globalData: {
    userInfo: null,
    localSocket: {},
    callback: function () {}
  },
  showLoad() {
    if(!isLoading) {
      wx.showLoading({
        title: '请稍后...',
      })
      isLoading = true
    }
  },
  hideLoad() {
    wx.hideLoading()
    isLoading = false
  },
  initSocket() {
    let that = this
    that.globalData.localSocket = wx.connectSocket({
      // url: 'wss://test.enzhico.net/app'
      url: 'wss://mapp.enzhico.net/app'
    })
    that.showLoad()
    that.globalData.localSocket.onOpen(function (res) {
      console.log('WebSocket连接已打开!readyState=' + that.globalData.localSocket.readyState)
      that.hideLoad()
      while (socketMsgQueue.length > 0) {
        var msg = socketMsgQueue.shift();
        that.sendSocketMessage(msg);
      }
    })
    that.globalData.localSocket.onMessage(function(res) {
      that.hideLoad()
      that.globalData.callback(res)
    })
    that.globalData.localSocket.onError(function(res) {
      console.log('readyState=' + that.globalData.localSocket.readyState)
    })
    that.globalData.localSocket.onClose(function (res) {
      console.log('WebSocket连接已关闭!readyState=' + that.globalData.localSocket.readyState)
      that.initSocket()
    })
  },
  //统一发送消息
  sendSocketMessage: function (msg) {
    if (this.globalData.localSocket.readyState === 1) {
      this.showLoad()
      this.globalData.localSocket.send({
        data: JSON.stringify(msg)
      })
    } else {
      socketMsgQueue.push(msg)
    }
  },
  onShow: function(options) {
    if (this.globalData.localSocket.readyState !== 0 && this.globalData.localSocket.readyState !== 1) {
      console.log('开始尝试连接WebSocket!readyState=' + this.globalData.localSocket.readyState)
      this.initSocket()
    }
  }
})

page 页面 

/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
  var that = this
  app.globalData.callback = function (res) {
   //res  接收websocket onMessage事件返回的数据
  }
}
//向服务器发送数据
app.sendSocketMessage(data: JSON.stringify({});
)

  

SocketTask

 这个对象是通过wx.connetSocket(obj)来获取的,他有一个属性值readyState,有4个状态值:

1 CONNECTING:0 连接中

2 OPEN:1 已连接

3 CLOSING:2 关闭中

4 CLOSED:3 已关闭

 刚开始我们使用的做法是全局一个变量socketOpen,用来表示这个socket是否打开,没有打开就重连,否则就直接调用发送消息接口了。但是经过测试发现网络不稳定,会出现这个变量没有得到及时更新一直是true。然后就不再去连接了,但实际上已经断开了

所以最后就把这个socketOpen变量去掉,直接判断SocketTask对象的属性值readyState,如果是1的话就表示直接可用;

来自:https://blog.csdn.net/h_a_h_ahahah/article/details/80645939

猜你喜欢

转载自www.cnblogs.com/xiaofenguo/p/10250455.html