The MQTT protocol is a machine-to-machine (M2M)/”Internet of Things” connectivity protocol.
Designed as an extremely lightweight publish/subscribe messaging transport, it is useful for
connections with remote locations where a small code footprint is required and/or network bandwidth is at a premium.
1 MQTT publish and subscribe
This code provides a client class which enable applications to connect to an MQTT broker to publish messages, and to subscribe to topics and receive published messages. It also provides some helper functions to make publishing one off messages to an MQTT server very straightforward.
Copy
// Connect to a mqtt broker // var mqtt = new Ax.net.MqttClient("tcp://test.mosquitto.org", "username", "password"); var mqtt = new Ax.net.MqttClient("tcp://test.mosquitto.org"); // Publish a message mqtt.publish("/test/xalpha", "subject123"); console.log("Start subscription"); // Subscribe for up to 500 messages to the topics var topics = ["test", "test/+"]; mqtt.subscribe(500, topics) // handle incoming messages .setOnMessage((topic, subject) => { console.log("=== MESSAGE ARRIVED ==="); console.log(" TOPIC:" + topic); console.log(" SUBJECT:" + subject); }) // handle exceptions .setOnConnectionLost(exception => { console.log("=== CONNECTION LOST ==="); console.log("EXCEPTION:" + exception); }) // wait up to 5 second to terminate (or before if all messages are consumed) .await(5); console.log("End program");