I have wriiten to publish a rfid value and while subscribing inside javascript, the socket connection is lost and I have attached the screenshot of my console.
value.php
<body> <div id="print"></div> <!-- jquery library --> <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> <!-- paho MQTT library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script> <script src="app.js"></script> </body>
I am trying to connect using hivemq broker and using port number of 8000 but it’s not connecting.
app.js
var hostname = "broker.hivemq.com"; var clientId = "someid"; var username = "username"; var password = "password"; var subscription = "sometopicname"; mqttClient = new Paho.MQTT.Client(hostname, 8000, clientId); mqttClient.onMessageArrived = MessageArrived; mqttClient.onConnectionLost = ConnectionLost; Connect(); function Connect() { mqttClient.connect({ onSuccess: Connected, onFailure: ConnectionFailed, userName: username, password: password, useSSL: false }); } function Connected() { console.log("Connected"); mqttClient.subscribe(subscription); } function ConnectionFailed(res) { console.log("Connection failed: " + res.errorMessage); } function ConnectionLost(res) { if (res.errorCode !== 0) { console.log("Connection lost:" + res.errorMessage); Connect(); } } function MessageArrived(message) { console.log(message.payloadString); }
Advertisement
Answer
First, are you 100% sure that port 8000 is configured to support MQTT over Websockets.
Second, you appear to have a hard coded clientId value, with this you will only be able to have 1 client connected at a time. EVERY Page needs to have a unique clientId, if you try and connect 2 clients with the same clientId (2 or more instances of the page in any browser) will kick the other one off the broker. ClientIds MUST be globally unique.
If after you have checked the first and fixed the second you should check the broker logs to see why it may be closing the connection.