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

'close' event triggered soon after the 'connect' event gets triggered #570

Closed
manju4ever opened this issue Mar 17, 2017 · 27 comments
Closed
Labels

Comments

@manju4ever
Copy link

manju4ever commented Mar 17, 2017

Hi All, here is my es6 file, please tell why the close event is trigerred immediately after connect

Node: 6.10.0

Running Docker Instance From : https://hub.docker.com/r/toke/mosquitto/~/dockerfile/

import mqtt from "mqtt";
import jsonfile from "jsonfile";
import path from 'path';

            let  default_options = {
                clientId: `cl_1234`,
                clean: false,
                keepalive: 10 * 1000,
                reconnectPeriod: 90000,
                connectTimeout: 30 * 1000,
                username: "",
                password: "",

            };

             //get broker info from the config file
            let config = jsonfile.readFileSync(path.resolve(process.env.CONFIG));

            //create a singleton, reuse the connection to broker

            const client = mqtt.connect(`mqtt://${config.mqtt.host}`, Object.assign(default_options, config.mqtt.options));

            client.on('connect', () => {
                    console.log(`|| Client - ${deviceId} - Connection to Broker OK !`);
            });

            client.on('reconnect', () => {
                    console.log(`|| Client - ${deviceId} - Connection to Broker Reconnected.`);
            })

            client.on('error', (err) => {
                     console.log(`|| Client - ${deviceId} - Connection to Broker Not Ok - ${err}!`)
            });

            client.on('close', () => {
                    console.log(`|| Client - ${deviceId} - Client Disconnected / Not able to connect to broker :( !`);
            });
export {client};

Is this the right way exporting the client object ?. Please do recommend me some best practices.

@manju4ever manju4ever changed the title Client Disconnects immediately after connection Client 'close' event triggered soon after the 'connect' event gets triggered Mar 17, 2017
@manju4ever manju4ever changed the title Client 'close' event triggered soon after the 'connect' event gets triggered 'close' event triggered soon after the 'connect' event gets triggered Mar 17, 2017
@milanito
Copy link

I have a similar issue.

It was working about 4 days ago, and now it does not. Here is what happened on our side :

  • It goes offline
  • It loops on reconnect and close

@mcollina
Copy link
Member

Is this a regression between v2.4.0 and v2.5.0?

@milanito
Copy link

@mcollina to be fully honest (not that I don't want to blame anyone else but us aha), I'm not 100% sure.

I'm testing on different environment and having the version downgrade to see if it is the case :

  • In local, it does break
  • On circleci, it did break (yeah I know), it built a few minutes ago

I'll let you know if I can find something more useful than this :/

@mcollina
Copy link
Member

@milanito if you understand what's happening, would you mind adding a failing unit test to reproduce and send a PR?

@milanito
Copy link

@mcollina If I'm able to, of course

@milanito
Copy link

From what I have seen at the moment :

  • when I use a RabbitMQ (version 3.6.6) with the MQTT plugin (targeting version 3.1.1) it does work, but there is an error saying :
close Error: premature close
    at Socket.onclose (/Users/....../node_modules/end-of-stream/index.js:44:67)
    at emitOne (events.js:101:20)
    at Socket.emit (events.js:188:7)
    at TCP._handle.close [as _onclose] (net.js:498:12)
  • when I use mosca it does not work with the example in the README, but if I do :
const server = new mosca.Server({
    host: 'localhost', // with this line
    port: 1883,
});

it works.

I did try to remove the host part and use either localhost or 127.0.0.1 for my client, it does not work.

I also did try to modify the default host in mosca (defaultsModern in the lib/options.js) which is null, by default. It does work when I remove then the host part.

So I guess, basically on my end, it is more a question of mosca to make my life complete ( :p ), but I can maybe head there to ask why the default host is null.

@mcollina
Copy link
Member

I'm a bit lost, as I am missing why the hostname at which the broker listen causes MQTT.js to error.

@milanito
Copy link

In my case, if I don't put the host in my options (in mosca) it does not work. I'll try to investigate this weekend what happening under the hood

@0x5e5e
Copy link

0x5e5e commented Apr 20, 2017

Having the same issue, it's driving me crazy - the same mqtt code works in one heroku instance I have but doesn't work in another instance that's exactly the same. It connects to the MQTT server just fine, but then throws a 'offline' event, then instantly attempts to reconnect again.

var mqttClient = mqtt.connect('mqtt://SERVER_ENDPOINT');

/** Emitted on successful connection */
mqttClient.on('connect', function() {
  console.log("[MQTT] Connected to MQTT server");
  mqttConnected = true;
  mqttClient.subscribe('reply');
});

/** Emitted on connection error */
mqttClient.on('error', function() {
  console.log("[MQTT] MQTT Error");
  mqttConnected = false;
});

/** Emitted on connection offline status */
mqttClient.on('offline', function() {
  console.log("[MQTT] Connection offline");
  mqttConnected = false;
});

@mcollina
Copy link
Member

mcollina commented May 1, 2017

It seems we can close this now. Feel free to open a new issue if it is still an issue.

@mcollina mcollina closed this as completed May 1, 2017
@RangerMauve
Copy link
Contributor

I'm getting this exact pattern on iOS when people are on their data plan. I've reverted to 1.4.1 which fixed the looping issue and I'm gonna see which version broke things and hopefully track the details down.

@RangerMauve
Copy link
Contributor

Upgrading from 2.4.0 to 2.8.2 made the issue worse. With 2.4.0 we were only seeing this happen when the app was in the background for a while, but with 2.8.2 it happens after the first time we connect. Sadly we can't debug the problem with breakpoints because connecting the debugger makes the problem go away.

@mcollina mcollina reopened this Jun 15, 2017
@mcollina
Copy link
Member

@RangerMauve can you upload a script/project that reproduces the problem, ideally just using Node.js? Or if you understand why this is happening, can you send a PR?

@RangerMauve
Copy link
Contributor

So far we're only seeing this happening on iOS when users are on a mobile network. I'm not yet sure if it's entirely the client-side that's causing trouble, or if it's related to our broker misbehaving.
My goal is to track down which release caused the problem to manifest and do a PR with a fix. :D

@RangerMauve
Copy link
Contributor

Seems that a change in 2.0.0 effected the issue. Gonna dig around in the code tomorrow.

@marleau
Copy link

marleau commented Oct 18, 2017

@RangerMauve Were you able to find a cause for this issue? I'm having a similar problem.

@RangerMauve
Copy link
Contributor

@marleau Sorry for the lack of follow up! Sadly I didn't find the issue and we ended up downgrading our version of mqtt.js for that project. 1.14.1 is what we're using actively right now and it's working fine for all use cases.

@jianfenkezhan
Copy link

How to fix it?

@github-actions
Copy link

This is an automated message to let you know that this issue has
gone 365 days without any activity. In order to ensure that we work
on issues that still matter, this issue will be closed in 14 days.

If this issue is still important, you can simply comment with a
"bump" to keep it open.

Thank you for your contribution.

@github-actions github-actions bot added the stale label Sep 23, 2022
@github-actions
Copy link

github-actions bot commented Oct 8, 2022

This issue was automatically closed due to inactivity.

@github-actions github-actions bot closed this as completed Oct 8, 2022
@jaganpaladin
Copy link

Hey, could anybody find a solution to this?

@robertsLando
Copy link
Member

@jaganpaladin did you tried with latest version?

@jaganpaladin
Copy link

Hey @robertsLando , I tried with 5.3.0. what version can should I try with?

@robertsLando
Copy link
Member

@jaganpaladin Could you provide a script to repro the issue?

@jaganpaladin
Copy link

jaganpaladin commented Dec 13, 2023

Hey @robertsLando , thanks for the prompt response. Here's a sample code.

function connectMQTT() {
  return mqtt.connect(connectUrl, {
    clientId,
    clean: true,
    connectTimeout: 4000,
    username: 'xxxxx',
    password: 'xxxxx',
  });
}

let mqttClient = connectMQTT()


mqttClient.on('connect', function () {
  console.log('Connected to MQTT broker');
});

// Handle MQTT errors
mqttClient.on('error', function (error) {
  console.log("Connection error", error)
   if (error && error.code === 2) {
    // Client ID rejection error (code 2)
    console.log('Client ID rejected. Reconnecting with a new client ID.');

    // Generate a new unique client ID
    const newClientId = generateUniqueClientId(); //  logic to generate a unique client ID (sample: emqx_cloud_1756)
    mqttClient = connectMQTT(newClientId); // Updating the mqttClient variable with the new client and the new client ID
  } else {
    // Other errors
    handleDisconnect();
  }
});

// Handle MQTT close
mqttClient.on('close', function () {
  console.log('MQTT Connection Closed');
  handleDisconnect();
  mqttClient = connectMQTT();
});

So, i'm trying to run this as a google cloud function so that i can return the mqtt response to my front end over a http based APIs.

Here's how it goes:

exports.helloWorld = functions.https.onRequest(async (req, res) => {
mqttClient.publish(topic, message)
mqttClient.subscribe(topic, callback function(){
})

}

Hope this helps.

@robertsLando
Copy link
Member

@jaganpaladin That piece of code is a standard mqtt client connection, I'm using mqttjs in lot of project both on frontend and backend side and I never faced such problem. I have a feel this is something related to broker side. I suggest you to try reproduce the issue using paho-mqtt or other mqtt clients to see if they have the same behaviour

@jaganpaladin
Copy link

Hi @robertsLando , thank you. I'll try that and let you know.

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

No branches or pull requests

9 participants