MQTT.js
MQTT.js copied to clipboard
why the client connected again and agian
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
Can you verify that this is not a problem with your broker?
generate unique id for different instance of the connection. same id disconnects all the time
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.
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?
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;`
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.
<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>
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.
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.