Try to start mosquitto broker with command mosquitto to see if it is working properly. Then we need a customized mosquitto config file, let’s call it mqtt.conf.
1 2 3 4 5
listener 1883 protocol mqtt
listener 1884 protocol websockets
Now when we start with the command mosquitto -c mqtt.conf, you should see something like this:
It is time for the websocket coming in. We need a mqtt javascript client here called mqttws31.js, available from Paho. An example code would look like:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html> <head> <title>Mosquitto Websockets</title> <script src="jquery.js" type="text/javascript"></script> <script src="mqttws31.js" type="text/javascript"></script> <script type="text/javascript"> var mqtt; var reconnectTimeout = 2000; var port = 1884; var host = "127.0.0.1" var topic = "+/#"
function MQTTconnect() { mqtt = new Paho.MQTT.Client( host, port, "client_X") ; var options = { timeout: 3, cleanSession: false, onSuccess: onConnect, onFailure: function (message) { $('#status').val("Connection failed: " + message.errorMessage + "Retrying"); setTimeout(MQTTconnect, reconnectTimeout); } };
If we start to send some messages from command like, we will get the data coming via mqtt through mosquitto broker and then via websocket published to js client.