gpt4 book ai didi

node.js - Node 应用程序之间通过 MQTT 进行简单通信

转载 作者:搜寻专家 更新时间:2023-11-01 00:39:16 24 4
gpt4 key购买 nike

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

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

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

随着这个工作的进行,我想通过用私有(private) 替换公共(public)代理 来继续前进。过了一会儿,我找到了 mqtt-server 作为 Node 包。

所以我尝试了以下作为第三个 Node 应用程序,它应该是 app1app2 的代理:

服务器(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.');
});

问题

app1app2中调整connection-Uris(都为ws://127.0.0.1:1884)后服务器应用接收所有已发布的消息识别出有人连接并收听特定主题

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

感谢任何帮助!提前致谢。

最佳答案

我也无法让 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://

开头

关于node.js - Node 应用程序之间通过 MQTT 进行简单通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40803508/

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