微信小程序使用MQTT

微信小程序使用MQTT,第1张

//引入mqtt的js包

var mqtt=require('../../utils/mqtt.min.js')

var client=null

Page({

  /**

   * 页面的初始数据

   */

  data: {

  },

  onLoad() {

  this.connectmqtt()

  },

  connectmqtt:function(){

   var that=this

   const options={

     connectTimeout:4000,//连接延时

     clientId:"PonyRemoteControl"+Math.ceil(Math.random()*10),    //昵称

     port:8084,//端口

     username:'',

     password:''

   }

   client=mqtt.connect('wxs://mqtt.****.cc/mqtt',options)//连接mqtt

   client.on('connect',(e)=>{

     console.log('服务器连接成功')

     client.subscribe('EquipmentEnd_RemoteControlCar',{qos:0},function(err){

 粗昌凯      if (!err) {

         console.log('订阅迅备成功')

        }

     })

   })

   //信息监听事件

   client.on('message',function(topic,message){

     console.log('收到:'+message.toString())

  岩唤 })

   client.on('reconnect',(error)=>{

     console.log('正在重连中',error)

   })

   client.on('error',(error)=>{

    console.log('连接失败',error)

  })

  }

})

第一步:

参考此库官方说数或州明:https://github.com/mqttjs/MQTT.js#browserify

npm install -g webpack // install webpack

cd node_modules/mqtt

npm install . // install dev dependencies

webpack mqtt.js ./my_mqtt.js --output-library-target commonjs2

第二步:

将生成的薯蔽my_mqtt.js文件里所有的

(function() { return this}())

替换为:

window

第三步:

在my_mqtt.js文件顶部加上代码:团裂

var setImmediate = setTimeout

var clearImmediate = clearTimeout

var socketOpen = false

var socketMsgQueue = []

function sendSocketMessage(msg) {

console.log('send msg:', typeof msg)

console.log(msg)

if (socketOpen) {

wx.sendSocketMessage({

data: msg

})

} else {

socketMsgQueue.push(msg)

}

}

var document = {

URL: ''

}

var window = {

setTimeout: setTimeout,

clearTimeout: clearTimeout,

WebSocket: function (url) {

console.log('call window WebSocket', arguments)

var ws = {

send: sendSocketMessage,

close: wx.closeSocket,

onopen: null,

onmessage: null,

onclose: null,

onerror: null

}

wx.connectSocket({ url: url })

wx.onSocketOpen(function (res) {

console.log('收到onopen事件:', arguments)

socketOpen = true

for (var i = 0i <socketMsgQueue.lengthi++) {

sendSocketMessage(socketMsgQueue[i])

}

socketMsgQueue = []

ws.onopen &&ws.onopen.apply(ws, arguments)

})

wx.onSocketMessage(function (res) {

console.log('收到onmessage事件:', arguments)

console.log(res.data)

ws.onmessage &&ws.onmessage.apply(ws, arguments)

})

wx.onSocketClose(function () {

console.log('收到onclose事件:', arguments)

ws.onclose &&ws.onclose.apply(ws, arguments)

})

wx.onSocketError(function () {

console.log('收到onerror事件:', arguments)

ws.onerror &&ws.onerror.apply(ws, arguments)

})

return ws

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12468929.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-25
下一篇 2023-05-25

发表评论

登录后才能评论

评论列表(0条)

保存