[英]mqtt async wait for concurrent messages then respond to respective http post requests
我有这个家庭自动化项目的过程。
下面是从另一个问题中提取的代码,因为它与我想要做的完全匹配。
此代码一次只能处理一个请求。 我应该怎么做来处理并发请求?
var resp;
var timeOutValue = 5000; //wait 5 seconds
var timer;
const client = mqtt.connect(MQTTServer)
client.on('message', (topic, message) => {
resp.send(message);
client.unsubscribe('inTopic');
resp = undefined;
clearTimeout(timer)
}
app.post('/test', function (request, response) {
resp = response;
client.publish ('outTopic' , 'request ');
client.subscribe('inTopic');
timer = setTimeout(function(){
if (resp) {
resp.send(message);
resp = undefined;
client.unsubscribe('inTopic');
}
}, timeOutValue);
}
我试过这个:
但我不知道它是否适用于并发请求,因为我是 nodejs 的新手。 所有这些都发生在 http post 路由处理程序中。
export async function scheduleMqtt() {
var topic= 'office/csb_1';
var topic1=topic;
console.log("MQTT is started")
var client = mqtt.connect(mqtturl, options);
client.on('connect', mqtt_connect);
function mqtt_connect() {
console.log('client has connected successfully');
client.subscribe(topic, 0, mqtt_subscribe);
client.on('message', mqtt_messsageReceived);
console.log(topic);
};
function mqtt_subscribe(err, granted) {
console.log("Subscribed to " + topic);
if (err) { console.log(err); }
console.log("Granted:")
console.log(granted)
client.publish(topic);
console.log("topic");
client.on('message', function (topic, message) {
console.log(message.toString()); //if toString is not given, the message comes as buffer
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.