关于javascript:微信小程序使用Stomp连接websockt

56次阅读

共计 1732 个字符,预计需要花费 5 分钟才能阅读完成。

const Stomp = require('./utils/stomp.js').Stomp;

/** 开启长连贯 */
  onConnectSocket() {
    var socketOpen = false
    var socketMsgQueue = []
    function sendSocketMessage(msg) {if (socketOpen) {
        wx.sendSocketMessage({data: msg})
      } else {socketMsgQueue.push(msg)
      }
    }

    /** 这里是连贯数据用的 */
    var websocketParams = {
      send: sendSocketMessage,
      onopen: null,
      onmessage: null,
      close: () => {if(this.client){this.client = null;}
      }
    }

    wx.connectSocket({url: 'wss://123456789.com:9000'})

    wx.onSocketOpen(function (res) {
      socketOpen = true
      for (var i = 0; i < socketMsgQueue.length; i++) {sendSocketMessage(socketMsgQueue[i])
      }
      socketMsgQueue = []
      websocketParams.onopen && websocketParams.onopen()})
    let list = this.globalData.equipmentList || [];

    wx.onSocketMessage((res) => {
        /** 解决数据   我这里后盾给我得数据是字符串,且须要截取  start*/
      var buffer = res.data;
      var dataview = new DataView(buffer);
      var ints = new Uint8Array(buffer.byteLength);
      var str = '';
      for (var i = 0; i < ints.length; i++) {str += String.fromCharCode(dataview.getUint8(i));
      }
      let params = str.indexOf("{") !== -1 ? str.slice(str.indexOf("{") - 1, str.lastIndexOf('}') + 1) : '';
        /** 解决数据   我这里后盾给我得数据是字符串,且须要截取  end*/

      if (params) {params = params.replace(/(\r\n|\n|\r)/gm, '');
        params = JSON.parse(params);
           list.push(params)
         this.globalData.equipmentList = list;
      }
      websocketParams.onmessage && websocketParams.onmessage(res);
    })

    /** 这里肯定要写  Stomp 小程序版没有 window 所以从新赋值 */
    Stomp.setInterval = function (interval, f) {return setInterval(f, interval);
    };
    
    /** 这里肯定要写  Stomp 小程序版没有 window 所以从新赋值 */
    Stomp.clearInterval = function (id) {return clearInterval(id);
    };

    this.client = Stomp.over(websocketParams);
    this.client.connect('账号', '明码',  (frame)=> {
       /** queue/MD210001 订阅队列 */
      this.client.subscribe(`/queue/MD210001`, function (txt) {})
      // this.client.send("/queue/MD210002", { priority: 9}, "Hello, MD210002");
    })
  },

/** 断开连接 */
  onCloseSocket(){if(this.client){
      this.client.disconnect(res=>{console.log("断开连接",res)
      })
      this.client = null;
    }
  },

正文完
 0