连接nodejs和云mqtt

新手上路,请多包涵

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

应用程序.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 **
    });
  });

});

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

原文由 Muhsin Keloth 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 349
2 个回答

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

应用程序.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
    });
});

原文由 Muhsin Keloth 发布,翻译遵循 CC BY-SA 3.0 许可协议

连接可能出错,尝试添加这个,我想你会看到一些东西:

 client.on('error', function(err) {
    console.log(err);
});

原文由 michelem 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题