我有这个用于家庭自动化项目的过程。
下面是从另一个question提取的代码,因为它与我要尝试执行的操作完全匹配。
此代码一次只能处理一个请求。如何处理并发请求?
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发布路由处理程序内。
答案 0 :(得分:0)
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
});
};