Broker和Publisher在一台计算机上运行,而订阅服务器在另一台计算机上运行。 问题:订户没有收到已发布的消息。
如果代理,发布者和订阅者在同一台计算机上运行,则代码可以正常工作。
subscriber.js
var client = mqtt.connect('mqtt://192.168.10.6:1234');
192.168.10.6:1234 是运行代理和发布者的计算机的IP地址。
Broker.js
const aedes = require('aedes')()
const server = require('net').createServer(aedes.handle)
const port = 1234
server.listen(port, function () {
console.log('server started and listening on port ', port)
})
Publisher.js
const express= require('express')
const mqtt = require('mqtt');
const app = express();
var client = mqtt.connect('mqtt://127.0.0.1:1234');
topic = "greeting";
msg = "hello";
app.get('/', (req,res) => {
client.publish(topic,msg);
res.send("Mqtt just published a message")
})
app.listen(5000);
Subscriber.js
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://192.168.10.6:1234');
topic = "greetings"
client.on('connect', ()=> {
client.subscribe(topic)
})
client.on('message', (topic, payload) => {
payload= payload.toString();
console.log(payload);
})