mqtt js 客户端接入

公司入手一个新任务,类似于一个网页版文字直播室,需要监听某个老师的消息。于是服务端搭建了mqtt服务。

网页版如何监听 对应的mqtt消息,怎么订阅,怎么建立链接呢。百度了一下,网上有开源的js 提供帮助。

地址如下: https://www.eclipse.org/paho/clients/js/

1.引入 js 

可以下载 download url https://raw.githubusercontent.com/eclipse/paho.mqtt.javascript/master/src/mqttws31.js

也可以用对应的cdn 地址 

For the plain library

For the minified library


2.代码示例

// Create a client instance
client = new Paho.MQTT.Client(location.hostname, Number(location.port), "clientId");

// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;

// connect the client
client.connect({onSuccess:onConnect});


// called when the client connects
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);
}

// called when the client loses its connection
function onConnectionLost(responseObject) {
  if (responseObject.errorCode !== 0) {
    console.log("onConnectionLost:"+responseObject.errorMessage);
  }
}

// called when a message arrives
function onMessageArrived(message) {
  console.log("onMessageArrived:"+message.payloadString);
}

你可能感兴趣的:(【mqtt】)