手把手教你玩转小程序websocket

原文链接:https://blog.csdn.net/qq_36436877/article/details/81780699?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.nonecase

第一步:创建一个 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();
  }
 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值