gpt4 book ai didi

javascript - 连接nodejs和云mqtt

转载 作者:数据小太阳 更新时间:2023-10-29 03:50:30 25 4
gpt4 key购买 nike

我正在做一个基于物联网的项目。所以我需要连接cloudmqttnodejs 服务器。

app.js

// Create a MQTT Client
var mqtt = require('mqtt');

// Create a client connection to CloudMQTT for live data
var client = mqtt.connect('xxxxxxxxxxx', {
username: 'xxxxx',
password: 'xxxxxxx'
});

client.on('connect', function() { // When connected
console.log("Connected to CloudMQTT");
// Subscribe to the temperature
client.subscribe('Motion', function() {
// When a message arrives, do something with it
client.on('message', function(topic, message, packet) {
// ** Need to pass message out **
});
});

});

然后启动我的服务器。但什么也没有发生(没有错误消息,也没有警告)。请帮我解决这个问题?

最佳答案

现在 cloudmqttnodejs 服务器通过提供额外的参数连接,例如 clientId、keepalive、protocolVersion 等。

app.js

var mqtt = require('mqtt');
var options = {
port: 15255,
host: 'mqtt://m11.cloudmqtt.com',
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
username: 'xxxxxxxxxxxxxxxxxx',
password: 'xxxxxxxxxxxxxxxxxx',
keepalive: 60,
reconnectPeriod: 1000,
protocolId: 'MQIsdp',
protocolVersion: 3,
clean: true,
encoding: 'utf8'
};
var client = mqtt.connect('mqtt://m11.cloudmqtt.com', options);
client.on('connect', function() { // When connected
console.log('connected');
// subscribe to a topic
client.subscribe('topic1/#', function() {
// when a message arrives, do something with it
client.on('message', function(topic, message, packet) {
console.log("Received '" + message + "' on '" + topic + "'");
});
});

// publish a message to a topic
client.publish('topic1/#', 'my message', function() {
console.log("Message is published");
client.end(); // Close the connection when published
});
});

关于javascript - 连接nodejs和云mqtt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36443406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com