我通过端口8081(websockets)建立了MQTT连接。 on消息接收回调除了我在脚本开头发送的“ test”消息外,不显示任何其他消息:
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("onConnect");
mqtt.subscribe("drivingStatus");
message = new Paho.Message("test");
message.destinationName = "drivingStatus";
mqtt.send(message);
}
此消息“测试”出现在onMessagedArrived函数中:
function onMessageArrived(message) {
console.log(message.payloadString)
// console.log("onMessageArrived:"+message.payloadString);
}
但是,当消息从python脚本(目标端口1883)发布到主题“ drivingStatus”时,该消息不会出现在控制台中。尽管该消息出现在MQTT经纪人控制台上。
Javascript Paho MQTT连接如何与MQTT代理正确同步?
预期的输出是所有消息都将显示在控制台中(如在输入命令mosquitto_sub -d -t drivingStatus
后通过终端订阅时所看到的那样)
整个代码是:
var mqtt
var reconnectTimeout = 2000
var host = "x"
var port = 8081
var r = Math.random().toString(36).substring(7);
var client = "hmack00" + r
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("onConnect");
mqtt.subscribe("drivingStatus");
message = new Paho.Message("test");
message.destinationName = "drivingStatus";
mqtt.send(message);
}
function onFailure(message) {
console.log("Connection Attempt to Host "+host+"Failed");
setTimeout(MQTTconnect, reconnectTimeout);
}
function onMessageArrived(message) {
console.log(message.payloadString)
// console.log("onMessageArrived:"+message.payloadString);
}
mqtt = new Paho.Client(host, port, client);
console.log("connecting to " + host)
var options = {
timeout: 3,
onSuccess: onConnect,
onFailure: onFailure,
};
mqtt.onMessageArrived = onMessageArrived;
mqtt.connect(options);