【问题标题】:Simple communication via MQTT between node apps节点应用程序之间通过 MQTT 进行简单通信
【发布时间】:2017-04-09 18:24:59
【问题描述】:

您好,我是 MQTT 的新手,最近几天我阅读了很多关于它的帖子和博客,但我似乎并不完全了解所需的不同部分,例如 Broker、Clients。

我希望两个节点应用程序通过本地 mqtt 服务相互通信。据我了解,这个mqtt服务叫做broker。我设法让 2 个节点应用程序通过这样的公共代理进行通信:

app1(发件人)

 const mqtt = require('mqtt');

 // to be changed to own local server/service
 const client = mqtt.connect('http://broker.hivemq.com');

 client.on('connect', () => {
     let id = 0;
     setInterval(() => {
         client.publish('myTopic', 'my message - ' + ++id);
     }, 3000);
 });

app2(接收方)

const mqtt = require('mqtt');

// to be changed to own local server/service
const client = mqtt.connect('http://broker.hivemq.com');

client.on('connect', () => {
    client.subscribe('myTopic');
});

client.on('message', (topic, message) => {
    console.log('MSG: %s: %s', topic, message);
});

由于这行得通,我想继续用 私人 代替 公共经纪人。过了一会儿,我发现 mqtt-server 作为一个节点包。

所以我尝试了以下作为第三个节点应用程序,它应该是 app1 和 app2 的代理:

服务器(MQTT 代理)

fs = require('fs');
mqttServer = require('mqtt-server');
let subscriptions = [];

let servers = mqttServer(
  // servers to start
  {
    mqtt: 'tcp://127.0.0.1:1883',
    mqttws: 'ws://127.0.0.1:1884',
  },
  // options
  {
    emitEvents: true
  },
  // client handler
  function (client) {
    client.connack({
      returnCode: 0
});

client.on('publish', (msg) => {
  let topic = msg.topic;
  let content = msg.payload.toString();
    // this works, it outputs the topic and the message.
    // problem is: app2 does not receive them.
    // do we have to forward them somehow here?
    console.log(topic, content);

    });

    client.on('subscribe', (sub) => {
      let newSubscription = sub.subscriptions[0];
      subscriptions.push(newSubscription);
      console.log('New subscriber to topic:', newSubscription.topic);
    });
  });

servers.listen(function () {
  console.log('MQTT servers now listening.');
});

问题

调整app1和app2中的connection-Uris(都为ws://127.0.0.1:1884)后,服务器应用接收所有发布的消息并且识别出有人联系并收听特定主题。

但是:当服务器获取所有这些事件/消息时,app2 不再接收这些消息。推断这一点,这个经纪人一定有问题,因为使用公共经纪人一切正常。

任何帮助表示赞赏!提前致谢。

【问题讨论】:

  • 更新问题以显示您将客户端连接网址更改为的确切内容。
  • 感谢您的建议 :) 已更新。
  • 第一个建议,如果你想让它保持基于 nodejs 或 mosquitto,尝试不同的代理,比如 Mosca
  • 我尝试了 mosca,但我没有让它正常工作,因为它需要 Redis(或其他数据库),我不明白如何让它运行/为什么仍然需要它。跨度>

标签: node.js mqtt


【解决方案1】:

我也无法让mqtt-server 工作,所以试试 Mosca。

如果你想发送 QOS1/2 消息,Mosca 只需要一个后端,没有它就可以工作。

var mosca = require('mosca');

var settings = {
    port:1883
}

var server = new mosca.Server(settings);

server.on('ready', function(){
  console.log("ready");
});

这将在端口 1883 上启动一个 mqtt 代理

您需要确保您的客户端连接的是原始 mqtt 而不是 websockets,因此请确保 url 以 mqtt:// 开头

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多