收藏
回答

小程序webSocket怎么用?

我的小程序能接收到心跳,但是接受不到推送消息

linkSocket(){
   
   var that=this;
    
   let obj = {
     userId: wx.getStorageSync('customId'),
     roleId: '-1',
     clientTypeId: '18',
     groupId: '1'
   };
   wx.connectSocket({
     url: 'wss://xxx.com:8989/ws/getPushMsg?userId=' + obj.userId + '&roleId=' + obj.roleId + '&clientTypeId=' + obj.clientTypeId + '&groupId=' + obj.groupId + '&token=SCAPPc11bd2e581e44125aea4f0e20980f75a5984',
     success() {
       console.log('连接成功')
       that.initEventHandle()
     }
   })
 },
 /**
  * 连接成功准备回话
  */
 initEventHandle(){
   var _this = this;
   const targetMap = {
     userId: wx.getStorageSync('customId'), //添加用户id
     groupId: "1", //添加机构id
     roleId: "-1", //添加角色id  机构2
     clientTypeId: "18", //大数据平台
   };
   let that = this
   let socketOpen=false;
   let socketMsgQueue = []
 
   wx.onSocketOpen(function (res) {
     console.log("open")
     socketOpen = true
     for (let i = 0; i < socketMsgQueue.length; i++) {
       sendSocketMessage(socketMsgQueue[i])
     }
     socketMsgQueue = []
     timer = setInterval(function () {
       sayMarco()
     }, 10000);
   })
   wx.onSocketError(function (res) {
     console.log('WebSocket连接打开失败')
   })
   wx.onSocketClose(function (res) {
     console.log('WebSocket 已关闭!')
   })
 
   function sendSocketMessage(msg) {
     console.log("ok")
     if (socketOpen) {
       wx.sendSocketMessage({
         data: msg
       })
       wx.onSocketMessage(function (res) {
         let str = res.data;
         var dbObj = JSON.parse(str);
         //isOil
         if (dbObj.autoDelete) {
           var obj = JSON.parse(dbObj.context);
           obj.isOil = _this.data.isOil;
           wx.navigateTo({
             url: '../payForCode/payForCode?jsondata=' + JSON.stringify(obj)
           })
         }
       })
     } else {
       socketMsgQueue.push(msg)
     }
   }
 
 
 
   function sayMarco() {
     console.log("心跳")
     
     let _targetMap = targetMap;
     let requestParamMap = {};
     requestParamMap["target"] = _targetMap;
     requestParamMap["contextType"] = 1; //内容类型-文本 标识当前消息内容的类型
     requestParamMap["context"] = "545sfd45g64s9df";
     requestParamMap["businessTypeCode"] = 0;
     requestParamMap["sendUser"] = _targetMap;
     requestParamMap["clientType"] = 18;
     //当前参数仅终端存在
     requestParamMap["msgType"] = 0; //请求类型/消息类型标识当前信息的作用
     sendSocketMessage(JSON.stringify(requestParamMap))
   }


最后一次编辑于  2019-12-11
回答关注问题邀请回答
收藏

1 个回答

  • 少年啦
    少年啦
    2019-12-11

    心跳也是接收数据的形式 既然可以 说明可能是你的服务器那边的问题吧

    2019-12-11
    赞同 1
    回复 4
    • 抱着嫦娥烤玉兔
      抱着嫦娥烤玉兔
      2019-12-11
      你看看我写的对吗
      2019-12-11
      回复
    • 抱着嫦娥烤玉兔
      抱着嫦娥烤玉兔
      2019-12-11
      这是心跳
      2019-12-11
      回复
    • 少年啦
      少年啦
      2019-12-11回复抱着嫦娥烤玉兔
      你把onSocketMessage方法先抽离出来 测试一下  先不要做那些判断
      2019-12-11
      回复
    • 抱着嫦娥烤玉兔
      抱着嫦娥烤玉兔
      2019-12-11回复少年啦
      抽离出来效果一样
      2019-12-11
      回复
登录 后发表内容
问题标签