小程序使用websoket

1.定义全局对象

//在app.js中定义全局对象
	globalData: {
		soketObj: {}
	}

2.封装创建soket方法

 connectSoket: function (callback) {
 	//url-需要后端提供链接地址 进行推送
    let sessionId = getApp().globalData.userInfo.session_id,
    url = `${config.wsHost}api/websocket_service/v1/ws/index?session_id=${sessionId}`;
    getApp().globalData.soketObj = wx.connectSocket({
      url: url
    });
    !!callback && callback();
 },

3.封装连接websoket方法

soketProMsg: function () { 
    var self = this;
    self.connectSoket(() => {
      let soketIo = getApp().globalData.soketObj;
      console.log("连接对象", soketIo)
      soketIo.onOpen((res) => {
        console.log("开启",res)
        soketIo.onMessage((result) => {
          result = JSON.parse(result.data);
          console.log("socket状态对象", result);
          switch (result.code) {
            case 101: //单条数据推送
              console.log("状态码101", result);
          	  //根据需求做相应的业务逻辑
              let oldIndex = 0
              self.data.behaviorList = self.data.behaviorList.map((item, index) => {
              	//单条数据下的子数据处理
                if (item.userId == result.data.userId) {
                  oldIndex = index;
                  item.time = self.getDateDiff(result.data.systemTime);
                  item.userData.forEach((cont) => {
                    if ((cont.type == 'cardView' && result.data.userData.type == 'cardView') || (cont.type == 'cardShare' && result.data.userData.type == 'cardShare')){
                      result.data.userData.time = cont.time + result.data.userData.time;
                    }
                  })
                  item.userData.unshift(result.data.userData);
                  if (item.userData.length > 10) { //超过10条删除多余数据
                    var itemLength = item.userData.length - 3;
                    item.userData.splice(3, itemLength);
                  }
                  var hash = {};  //过滤掉相同类型的数据
                  item.userData = item.userData.reduce(function (item, next) {
                    hash[next.type] ? '' : hash[next.type] = true && item.push(next);
                    return item
                  }, [])
                }
                item.userData.forEach((n) => { //组装数据
                  //这个方法是组装单条数据中的不同类型
                  self.behaviorDataProcess(n)
                })
                return item;
              });
			  //单条数据处理,最新的放在前面
              if (oldIndex > 0) {
                const item = self.data.behaviorList[oldIndex]
                self.data.behaviorList.splice(oldIndex, 1);
                self.data.behaviorList.unshift(item)
              }
			  //behaviorList组装好后的数据
              self.setData({
                behaviorList: self.data.behaviorList
              })
              break;
          }
        })
      })
      
    })
  },

4.推送时间处理

  //根据单条数据返回的时间戳处理更新时间-兼容安卓机时间转换无效问题
  getDateDiff: function(dateTimeStamp){
    var minute = 1000 * 60, //用毫秒显示
        hour = minute * 60,
        day = hour * 24,
        halfamonth = day * 15,
        month = day * 30,
        now = new Date().getTime(),
        diffValue = now - dateTimeStamp,
        monthC = diffValue / month, 
        weekC = diffValue / (7 * day),
        dayC = diffValue / day,
        hourC = diffValue / hour,
        minC = diffValue / minute,
        result = '';
    
    var oldTime = this.getMyDate(dateTimeStamp), //获取具体时间
        aindex = oldTime.indexOf(' '),
        specificTime = oldTime.substring(aindex + 1, oldTime.length),
        yearTime = oldTime.substring(aindex + 1, 0);
    if(monthC>= 1){
      // result = "" + parseInt(monthC) + "月前 " + "specificTime";
      result = "" + yearTime; //超过一月显示年月日
    }
    else if (weekC >= 1) {
      // result = "" + parseInt(weekC) + "周前";
      result = "" + yearTime ; //超过一周显示年月日
    }
    else if (dayC >= 1) {
      result = "" + parseInt(dayC) + "天前 " + specificTime;
    }
    else if (hourC >= 1) {
      result = "" + parseInt(hourC) + "小时前";
    }
    else if (minC >= 1) {
      result = "" + parseInt(minC) + "分钟前";
    } else{
      result = "刚刚";
    }
    return result;
  },
  // 时间戳转日期
  getMyDate: function (str){
    if(str > 9999999999) { // 这里判断:时间戳为几位数
      var c_Date = new Date(parseInt(str));
    } else {
      var c_Date = new Date(parseInt(str) * 1000);
    }
    var c_Year = c_Date.getFullYear(),
      c_Month = c_Date.getMonth() + 1,
      c_Day = c_Date.getDate(),
      c_Hour = c_Date.getHours(),
      c_Min = c_Date.getMinutes(),
      c_Sen = c_Date.getSeconds();
      var c_Time = c_Year + '/' + this.getzf(c_Month) + '/' + this.getzf(c_Day) + ' ' + this.getAPHour(this.getzf(c_Hour)) + ':' + this.getzf(c_Min) + " ";
    return c_Time;
  },
  //补0操作  小于10的就在数字前面加0
  getzf: function (c_num){
    if(parseInt(c_num) < 10){
      c_num = '0' + c_num;
    }
    return c_num; 
  },
  //13点-24点减去12小时显示
  getAPHour: function (hour) {
    if (hour > 12) {
      return hour - 12;
    }
    return hour;
  }

注意

1.第一次进入界面还需要一个初始化的数据,这是个单独的接口,后面的soket推送则是更新初始化返回的数据;
2.在onShow中先调初始化数据接口,在调用 this.soketProMsg();
3.切换页面时需要关闭连接不然会导致连接多开 onHide中 wx.closeSocket(); //关闭连接
4.最重要的还是前三步,其他的根据需求来组装数据
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值