Search code examples
javascriptwebsocketmqttiotpaho

connect webpage through web socket to MQTT broker


i created mqtt broker at cloudMQTT and here is the info about ports & server that i got

click to see image of ports

now i wrote that code to run web page that connect to that broker and send hello world.

<html>
   <head>
      <title>JavaScript MQTT WebSocket Example</title>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript">
     </script>
     <script type = "text/javascript" language = "javascript">
        var mqtt;
        var reconnectTimeout = 2000;
        var host="m23.cloudmqtt.com"; //change this
        var port= 38788;

        function onConnect() {
      // Once a connection has been made, make a subscription and send a message.

        console.log("Connected ");
        //mqtt.subscribe("sensor1");
        message = new Paho.MQTT.Message("Hello world");
        message.destinationName = "orange1";
        mqtt.send(message);
      }
      function MQTTconnect() {
        console.log("connecting to "+ host +" "+ port);
        mqtt = new Paho.MQTT.Client(host,port,"clientjs");
        //document.write("connecting to "+ host);
        var options = {
            timeout: 3,
            onSuccess: onConnect,

         };

        mqtt.connect(options); //connect
        }

      </script>
   </head>
     <body>
   <h1>Main Body</h1>
    <script>
    MQTTconnect();
    </script>
   </body>
</html>

every time i open that page and open console.js i got that problem message:

error message that appear at console.log

(here are list of errors that appears at my console.log .. to help anyone who can see images) WebSocket connection to 'ws://m23.cloudmqtt.com:38788/mqtt' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET mqttws31.js:979

Paho.MQTT.ClientImpl._doConnect @ mqttws31.js:979

Paho.MQTT.ClientImpl.connect @ mqttws31.js:849

Client.connect @ mqttws31.js:1799

MQTTconnect @ websockets-1.htm:31

(anonymous) @ websockets-1.htm:39

WebSocket connection to 'ws://m23.cloudmqtt.com:38788/mqtt' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET mqttws31.js:977

Paho.MQTT.ClientImpl._doConnect @ mqttws31.js:977

Paho.MQTT.ClientImpl._disconnected @ mqttws31.js:1459

Paho.MQTT.ClientImpl._on_socket_error @ mqttws31.js:1347

(anonymous) @ mqttws31.js:157

i tried to change the ports but i got the same problem. how can i fix something like that ? and if i tried to connect to https://test.mosquitto.org/ i got the same problem ? how can this be fixed too ?


Solution

  • You need to set the flag to enable SSL (as the picture of the ports suggests TLS is required for Websockets)

    var options = {
      timeout: 3,
      onSuccess: onConnect,
      useSSL: true
    };