Paho JavaScript Client 基于websocket实现 mqtt客户端

编写客户端页面,引入Paho官方客户端js库

贴出关键代码如下:

// 创建客户端实例
//注意不要在client前写var
client = new Paho.MQTT.Client(location.hostname, Number(location.port), "clientId");

// 设置回调处理程序
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;

// 连接客户端
client.connect({onSuccess:onConnect});


// 客户端连接时调用
function onConnect() {
  // 建立连接后,进行订阅并发送消息。
  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);
}

原网站:https://blog.51cto.com/u_3423936/5062986

posted @ 2022-04-19 17:22  虚无——缥缈  阅读(404)  评论(0编辑  收藏  举报