moscajs / mosca

MQTT broker as a module
mosca.io
3.2k stars 513 forks source link

client.on get stuck waiting for message #796

Open pejoujarrar opened 5 years ago

pejoujarrar commented 5 years ago

`exports.get_live_measure = function(req, res) { var client = mqtt.connect('mqtt://192.168.1.193'); client.publish(req.params.typeId,req.params.sensorId) client.subscribe('response') client.on('message', function (topic, message) { res.json(message.toString()); client.end(); });

};`

In this code, when i'm sending an API call for some devices who are not supposed to give a response, the code get stuck at the instruction client.on('message').

Is there any way to skip stop/skip the instruction after an amount of time? or a way to manage this situation.

crapthings commented 5 years ago

what if put subscribe and onMessage after connected?

const mqtt = require('mqtt')

const client  = mqtt.connect('mqtt://localhost')

client.on('connect', function () {
  client.subscribe('converted', function (err) {
    if (err) return
    client.on('message', function (topic, message) {
      const result = JSON.parse(message.toString())
      console.log(result)
    })
  })
})
pejoujarrar commented 5 years ago

@crapthings thanks for the answer, but unfortunately nothing changes. the problem actually comes from the client.on("message") which enter in an infinite loop waiting for the response, but for an inexistant device there is no response, consequently, it will stick permanently there waiting for a never sent response, until i restart the server.