手把手教你玩轉小程序websocket

第一步:創建一個 WebSocket 連接

 wx.connectSocket({
      url: "wss://websocket.allhjs.com",
    })

第二步:監聽WebSocket連接打開

    wx.onSocketOpen(res => {
      this.setData({ socketOpen: true })
    })

第三步: wx.onSocketOpen 回調之後發送消息

 if (socketOpen) {
    wx.sendSocketMessage({
      data:msg
    })
  }

第四步:監聽服務器返回的消息

wx.onSocketMessage(function(res) {
  console.log('收到服務器內容:' + res.data)
})

第五步:由於同時只能有2個websocket,所以頁面卸載要關閉websocket

onUnload:function(){
    wx.closeSocket();
  },

下面貼上項目中一個完整的代碼

  //發表評論
  sendChat(){
    if (!this.data.chatInfo){
      util.showToast('評論內容不能爲空','none');
      return;
    }
    let params = {
      meetingId: this.data.meetingId,
      content: this.data.chatInfo
    }
    this.websocket(this.data.chatInfo,params);
  },
  //連接websocket
  websocket(msg,params){
    let socketOpen = this.data.socketOpen;
    let obj = {
      name: this.data.userInfo.nickName,
      userId: this.data.userId,
      meetingId: this.data.meetingId,
      addTime: util.formatTime(new Date()),
      content: msg
    }
    if (socketOpen){
      wx.sendSocketMessage({
        data: "{'userId':" + wx.getStorageSync('userId') + ",'databagId':" + this.data.meetingId + ",'msg':" + msg + ",'name':" + this.data.userInfo.nickName + "}",
        success:r =>{
          util.request(api.sendChats, params).then(r => {
            this.setData({ chatInfo: '' })
          })
        },
        fail:err =>{
          util.showToast('服務器已斷開','none')
          wx.connectSocket({
            url: "wss://websocket.allhjs.com?databagId=" + this.data.meetingId + "&userId=" + wx.getStorageSync('userId') + "&name=" + this.data.userInfo.nickName,
          })
          wx.onSocketOpen(res => {
            this.setData({ socketOpen: true })
          })
          console.log('err',err)
        }
      })
    }else{
      util.showToast('通信錯誤,請返回重連','none')
    }
  },
  onLoad: function(options) {
    this.getActDeatil(options.id);
    this.setData({ userId: wx.getStorageSync('userId'),userInfo: wx.getStorageSync('userInfo'), meetingId: options.id })
    //建立websocket
    wx.connectSocket({
      url: "wss://websocket.allhjs.com?databagId=" + this.data.meetingId + "&userId=" + wx.getStorageSync('userId') + "&name=" + this.data.userInfo.nickName,
    })
    wx.onSocketOpen(res => {
      this.setData({ socketOpen: true })
    })

    wx.onSocketError(res => {
      console.log('WebSocket連接打開失敗,請檢查!')
    })

    wx.onSocketMessage(res => {
      let chatList = this.data.chatList;
      let obj = JSON.parse(res.data);
      let params = {
        addTime: util.formatTime(new Date()),
        content: obj.msg,
        name: obj.name,
        userId: obj.userId
      }
      chatList.push(params);
      this.setData({ chatList })
      setTimeout(() => { this.setData({ toView: 'bottom' }) }, 1)
    })
  },
  onUnload:function(){
    wx.closeSocket();
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章