MQTT

MQTT主要使用在物联网中,是一种双工通信,属于ws协议长连接

that.client =new Paho.MQTT.Client(

ip, Number(port),"/ws",ID);

//ip:服务器IP;

port:服务器端口;

'/ws':固定就是ws协议;

ID:自己随便编一个字符串;

that.client.connect({useSSL:false,onSuccess:onConnect});

useSSL:是否保密;

onSuccess:链接成功后执行的回调函数;

function onConnect() {

       console.log("onConnected");

      //订阅的主题

      let id = localStorage.getItem("cncId");

      console.log(id);

      var topic ="/cnc/" +  id +"/servo_loading";

      console.log(topic);

      //订阅主题

      that.client.subscribe(topic);

      console.log("subscribed");

}

that.client.onConnectionLost =onConnectionLost;

//注册连接断开处理事件

that.client.onMessageArrived =onMessageArrived;

//注册消息接收处理事件

function onConnectionLost(responseObject) {

     if (responseObject.errorCode !==0) {

           console.log("onConnectionLost:"+responseObject.errorMessage);

            console.log("连接已断开");

      }

};


function onMessageArrived(message) {

    //console.log("收到消息:"+message.payloadString);

    //console.log("主题:"+message.destinationName);

    //that.msg = JSON.parse(message.payloadString);

     that.msg = JSON.parse(message);

     console.log(that.msg);

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容