paho连接前端界面的MQTT消息的api

223 阅读1分钟
// 创建一个jsMQTT客户端实例,clientId是唯一标识符,地址和端口号为服务的地址和端口
client = new Paho.MQTT.Client(location.hostname, Number(location.port), "clientId");

// 客户端连接丢失的处理
client.onConnectionLost = onConnectionLost;
//客户端收到消息时执行的方法
client.onMessageArrived = onMessageArrived;
//启动链接,在这里可以填入许多参数详情请看官网介绍
client.connect({onSuccess:onConnect});


// 回掉函数
function onConnect() {
  // Once a connection has been made, make a subscription and send a message.
  console.log("onConnect");
  client.subscribe("World");
  message = new Paho.MQTT.Message("Hello");
  message.destinationName = "World";
  client.send(message);
}

// 当客户端失去连接时调用
function onConnectionLost(responseObject) {
  if (responseObject.errorCode !== 0) {
    console.log("onConnectionLost:"+responseObject.errorMessage);
  }
}

// 受到消息时调用
function onMessageArrived(message) {
  console.log("onMessageArrived:"+message.payloadString);
}