js 使用Paho.mqtt连接mqtt 请给出完整示例
时间: 2023-11-19 15:05:37 浏览: 88
Qt Mqtt连接阿里云示例
4星 · 用户满意度95%
好的,以下是使用Paho.mqtt连接mqtt的js示例代码:
```javascript
// 引入Paho.mqtt
import Paho from 'paho-mqtt';
// 定义mqtt连接参数
const mqttHost = 'your_mqtt_host';
const mqttPort = 'your_mqtt_port';
const mqttClientId = 'your_mqtt_client_id';
const mqttUsername = 'your_mqtt_username';
const mqttPassword = 'your_mqtt_password';
// 创建mqtt客户端
const mqttClient = new Paho.Client(mqttHost, mqttPort, mqttClientId);
// 连接mqtt
mqttClient.connect({
onSuccess: () => {
console.log('mqtt连接成功');
// 连接成功后订阅主题
mqttClient.subscribe('your_topic', {
onSuccess: () => {
console.log('mqtt订阅成功');
},
onFailure: (err) => {
console.log(`mqtt订阅失败: ${err.errorMessage}`);
},
});
},
onFailure: (err) => {
console.log(`mqtt连接失败: ${err.errorMessage}`);
},
userName: mqttUsername,
password: mqttPassword,
});
// 监听mqtt消息
mqttClient.onMessageArrived = (message) => {
console.log(`收到mqtt消息: ${message.payloadString}`);
};
// 发布mqtt消息
const publishMessage = (topic, payload) => {
const message = new Paho.Message(payload);
message.destinationName = topic;
mqttClient.send(message);
};
```
上述代码中,我们首先引入了Paho.mqtt库,然后定义了mqtt连接参数。接着创建了mqtt客户端,然后调用`connect`方法连接mqtt,连接成功后订阅主题。最后,我们监听mqtt消息,收到消息后打印出来,同时提供了一个`publishMessage`函数用于发布mqtt消息。
阅读全文