MQTT.js icon indicating copy to clipboard operation
MQTT.js copied to clipboard

why the client connected again and agian

Open tmztliusf opened this issue 6 years ago • 8 comments

  client.on('connect', function () {           
   });
   client.on(  "message", function( topic, message, packet ){                
        console.log( "message:" + message );      
    });
   // 
   setInterval(function(){
        console.log( client.connected );                
    }, 100);
//true
//true
//false
//false

tmztliusf avatar Nov 06 '18 03:11 tmztliusf

Can you verify that this is not a problem with your broker?

mbrandau avatar Dec 10 '18 20:12 mbrandau

generate unique id for different instance of the connection. same id disconnects all the time

raevillena avatar Mar 01 '19 03:03 raevillena

Did anyone manage to solve it? I'm using React and every time I make a client.publish() it adds an extra connection to the broker.

chacalgbi avatar Aug 01 '22 01:08 chacalgbi

Did anyone manage to solve it? I'm using React and every time I make a client.publish() it adds an extra connection to the broker.

solved this ages ago, can you provide snippets how you instantiate and use the client?

raevillena avatar Aug 01 '22 09:08 raevillena

Alguém conseguiu resolver? Estou usando o React e toda vez que faço um client.publish() ele adiciona uma conexão extra ao broker.

resolvido isso há muito tempo, você pode fornecer trechos de como você instancia e usa o cliente?

I've tried several variations of the code below, and a few others available in the documentation.

`import React, {useState, useEffect} from 'react'; import './App.css'; import mqtt from "precompiled-mqtt"

function App() { const subscribles = ['/Antonio/Device1/led', '/Antonio/Device1/temp'] const [port, setPort] = useState(0) const host = "wss://user:[email protected]" const options = { clientId : "Thome" , clean: false } const client = mqtt.connect(host, options)

const handleClick = ()=>{ const y = port + 1 setPort(y) client.publish('/Antonio/Device1/Porta', y.toString(), {qos: 0, retain: true}, (callback, err) =>{ if(err) {console.log('ERRO publish packet: ', err) }}) }

useEffect(() => { client.on('connect', function(connack) { console.log("Conectado: ", connack) client.subscribe(subscribles, {nl: true, rap: true}, function (err, granted) { if (!err) { console.log("Inscrito com sucesso: ", granted) }else{ console.log("Erro ao Inscrever", err) } }) }) }, [])

client.on('message', function(topic, message) { console.log(topic.toString() + " - " + message.toString())}) client.on("error", function(error){ console.log("ERRO: " + error)}) client.on("close", function() { console.log("Connection closed by client") }) client.on("reconnect", function() { console.log("Client trying a reconnection") }) client.on("offline", function() { console.log("Client is currently offline") })

return ( <div className="App"> <header className="App-header"> <button onClick={handleClick} >Port: {port} ); }

export default App;`

chacalgbi avatar Aug 01 '22 10:08 chacalgbi

Did anyone manage to solve it? I'm using React and every time I make a client.publish() it adds an extra connection to the broker.

solved this ages ago, can you provide snippets how you instantiate and use the client?

If I use this example made for CDN directly in the Chrome browser, it works perfectly, creating only a connection with the Broker, maintaining it, reconnecting, etc... Only with react this happens.

Example
<script>
  let estado = false;
  const client = mqtt.connect('wss://user:pass@:narrowbane896.cloud.shiftr.io', {
    clientId: 'Navegador'
  });

  client.on('connect', function() {
    console.log('connected!');
    client.subscribe('/Antonio/Device2/tensao');
  });

  client.on('message', function(topic, message) {
    console.log(topic + ': ' + message.toString());
  });

  document.querySelector('button').addEventListener('click', function() {
    estado = !estado;
    client.publish('Luis/Arduino/PortaFrente', `${estado}`);
  });
</script>

chacalgbi avatar Aug 01 '22 10:08 chacalgbi

Did anyone manage to solve it? I'm using React and every time I make a client.publish() it adds an extra connection to the broker.

solved this ages ago, can you provide snippets how you instantiate and use the client?

If I use this example made for CDN directly in the Chrome browser, it works perfectly, creating only a connection with the Broker, maintaining it, reconnecting, etc... Only with react this happens.

Example Click Me ```

I meant to ask for the code snippets using react. Implementation goes like this I believe: instantiate the client at one of the highest order components (assuming this component gets loaded only once), export that client object and import in other component. You dont reinstantiate the component again, you can just call the methods using the imported instance. Does that make sense? Of course when you reload the app it reconnects again. But you should be expecting this to connect only once.

raevillena avatar Aug 01 '22 11:08 raevillena

Did anyone manage to solve it? I'm using React and every time I make a client.publish() it adds an extra connection to the broker.

solved this ages ago, can you provide snippets how you instantiate and use the client?

If I use this example made for CDN directly in the Chrome browser, it works perfectly, creating only a connection with the Broker, maintaining it, reconnecting, etc... Only with react this happens.

Example Click Me ```

I meant to ask for the code snippets using react. Implementation goes like this I believe: instantiate the client at one of the highest order components (assuming this component gets loaded only once), export that client object and import in other component. You dont reinstantiate the component again, you can just call the methods using the imported instance. Does that make sense? Of course when you reload the app it reconnects again. But you should be expecting this to connect only once.

The code with REACT is above this example that I put with pure html.

I put the connection inside useEffect(()=>{ client.on('connect', ()=> { console.log(Connected to Broker) }) },[ ])

so that it only happens once. But every time I click a button to publish, it adds a connection to the broker.

chacalgbi avatar Aug 01 '22 11:08 chacalgbi