Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble to get MQTT JavaScript Client running

I try to get a MQTT JavaScript Client running. It's based on the Eclipse Paho Client Library (org.eclipse.paho.mqtt.javascript.git).

Before running the JavaScript Client I was performing some tests with

  • mosquitto_pub -h test.mosquitto.org -t "/topic1" -m "test"

and

  • mosquitto_sub -h test.mosquitto.org -t "/topic1" -v

which are working fine.

Then I called my own mqttTest.html which contains:

<!DOCTYPE html>
<head>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  <script type="text/JavaScript" src="mqttws31.js"></script>
  <script type="text/JavaScript">

  var client;

  function doConnect() {

    client = new Messaging.Client("test.mosquitto.org", 1883, "mosqOtti");
    console.log("Client instantiated.");
    client.startTrace();
    console.log("Now trying to connect...");
    client.connect({onSuccess:onConnect});

  }

  function onConnect() {

    console.log("connection established");
    doSubscribe();

  }

  function doSubscribe() {

      client.subscribe("/topic1");

  }

  window.onload = function() {

      this.doConnect();

  }

</script>
</head> 

.
.
.

</body>
</html>

I tried to lauch this in Firefox. The debug console output tells me that

[09:58:27.825] Firefox can't establish a connection to the server at ws://test.mosquitto.org:1883/mqtt. @ file:///mqttws31.js:914

I know that moquitto does not support websockets natively. But I red that the lighttp running on test.mosquitto.org has mod_websockets installed.

Line 914 of mqttws31.js is trying to do this.socket = new WebSocket(wsurl, 'mqttv3.1');

So it seems that

  • either websockets doesn't really work for test.mosquitto.org
  • or my example is buggy!

I stuggled around for a long time now and need to get a JavaScript MQTT Client running.

Does anyone have an idea? Or another approach? Socket.IO seems not to be the right solution too.

Thanks very much in advance!

like image 414
marrrschine Avatar asked Mar 23 '23 12:03

marrrschine


1 Answers

As @hardillb says, the port you are using is incorrect. 1883 on test.mosquitto.org is solely for mqtt. If you wish to use websockets you need to connect using port 80. You should just be able to change your url to ws://test.mosquitto.org:1883/mqtt which presumably means changing your code to

client = new Messaging.Client("test.mosquitto.org", 80, "mosqOtti");

There is a websockets example (based on this code) running at http://test.mosquitto.org/sys/. Although it uses the deprecated mosquitto javascript client, it should demonstrate that it works.

The lighttpd config on test.mosquitto.org is:

websocket.server = (
    "/mqtt" =>
    (  
        "host" => "127.0.0.1",
        "port" => "1883",
        "subproto" => "mqttv3.1",
        "type" => "bin"
    )
)
like image 165
ralight Avatar answered Apr 01 '23 05:04

ralight