mqtt js 客户端接入

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u014756827/article/details/80008123

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript"></script>

For the minified library

<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>

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);
}

展开阅读全文

没有更多推荐了,返回首页