Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Connect after constructing client #1557

Closed
nandlab opened this issue Nov 17, 2022 · 3 comments
Closed

Connect after constructing client #1557

nandlab opened this issue Nov 17, 2022 · 3 comments

Comments

@nandlab
Copy link

nandlab commented Nov 17, 2022

Is there a way to first construct the client object with certain options and later connect to the broker?
In some use cases it would be more convenient.

@rrebase
Copy link

rrebase commented Feb 15, 2023

I'd also find it useful to have a simple way of constructing the client object. Use case: add events listeners to f.e. packetsend, packetreceive before actually connecting to the broker.

@Vincent-SV
Copy link

Vincent-SV commented May 12, 2023

I was looking exactly for this, because in the python package you create the client, then declare the callbacks, then use a .connect() method.
In the official documentation for this node mqtt package, this code is provided :

const mqtt = require('mqtt')
const client  = mqtt.connect('mqtt://test.mosquitto.org')

client.on('connect', function () {
  client.subscribe('presence', function (err) {
    if (!err) {
      client.publish('presence', 'Hello mqtt')
    }
  })
})

client.on('message', function (topic, message) {
  // message is Buffer
  console.log(message.toString())
  client.end()
})

And the "on connect" callback is declared after the connection, which bothers me a lot.
From what I understand, we send a CONNECT packet, and then while waiting for the CONNACK response, we declare what to do in case we get a CONNACK packet. It seems a bit risky to me, especially with bigger code, the CONNACK could arrive before we decide what to do with it and it could be ignored, thus skipping the subscriptions part !

This could cause #1153 for example.

I posted a question on stackoverflow : https://stackoverflow.com/questions/75548005/nodejs-mqtt-connection-and-callback-order-is-wrong/76229305?noredirect=1#comment134428767_76229305 but I got no satisfactory answers.

@robertsLando
Copy link
Member

MQTT 5.0.0 BETA is now available! Try it out and give us feedback: npm i mqtt@beta. It may fix your issues

Now you can do this by using the manualConnect option and calling connect method right after creating it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants