Thursday, November 30, 2023
ExplainerInternet of ThingsIoT ProtocolsIoT Software&ToolsTutorials/DIY

Connecting to VerneMQ Tutorial

Here You find some way, Connecting to VerneMQ. VerneMQ is most popular MQTT broker.

What is VerneMQ ?

VerneMQ is an enterprise ready, high-performance, distributed MQTT message broker. It scales horizontally and vertically on commodity hardware to support a high number of concurrent publishers and consumers while maintaining low and predictable latency and fault tolerance. It plugins can be developed in Erlang, Elixir, Lua, and any programming language that can implement HTTP WebHooks. It uses modern broadcast protocols and LevelDB for state replication in a cluster. It is Open Source and Apache2 licensed.

It is first and foremost a MQTT publish/subscribe message broker which implements the OASIS industry standard MQTT protocol. But VerneMQ is also built to take messaging and IoT applications to the next level by providing a unique set of features related to scalability, reliability and high-performance as well as operational simplicity.

To achieve these goals VerneMQ is designed from the ground up to work as a distributed message broker, ensuring continued operation in the event of node or network failures and easy horizontal scalability. The underlying technology is a proven telecom grade technology stack providing a rock solid foundation for systems that must be in continuous operation around the clock. It’s also able to make efficient use of all available resources as a basis for easy vertical scalability.

It uses a master-less clustering technology. There are no special nodes like masters or slaves to consider when the inevitable infrastructure changes or maintenance windows require adding or removing nodes. This makes operating the cluster safe and simple. MQTT 5.0 support now available.

If you know more about VerneMQ ,  Visit this link

Recommended : How To Install VerneMQ on UbunTu, RHEL, Docker, Debian and CentOS

Connecting to VerneMQ

As MQTT is the main application protocol spoken by VerneMQ, you could use any protocol compliant MQTT client library. Here you find some overview of the different options you have.


Use Mosquitto C library. A simple example looks like the following:

    #include <stdio.h>
    #include <mosquitto.h>

    /* Compile with: cc -o sub sub.c -lmosquitto  */

    void on_connect(struct mosquitto *mosq, void *userdata, int rc)
        mosquitto_subscribe(mosq, NULL, "$SYS/#", 0);

    void on_message(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *m)
        printf("%s %s\n", m->topic, m->payload);

    int main(int argc, char **argv)
        struct mosquitto *mosq;
        int rc;


        mosq = mosquitto_new(NULL, true, (void *)NULL);
        if (!mosq) {
            fprintf(stderr, "Error: Out of memory.\n");
            return (1);

        mosquitto_connect_callback_set(mosq, on_connect);
        mosquitto_message_callback_set(mosq, on_message);

        rc = mosquitto_connect(mosq, "", 1883, 60);
        if (rc) {
            fprintf(stderr, "Unable to connect (%d).\n", rc);
            return (rc);

        mosquitto_loop_forever(mosq, -1, 1);

        /* Unreached */

        return (0);


Use the official Paho MQTT client library. A simple example looks like the following:

    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
    int rc = 0;
    char buf[200];
    MQTTString topicString = MQTTString_initializer;
    char* payload = "mypayload";
    int payloadlen = strlen(payload);int buflen = sizeof(buf);

    data.clientID.cstring = "me";
    data.keepAliveInterval = 20;
    data.cleansession = 1;
    len = MQTTSerialize_connect(buf, buflen, &data);

    topicString.cstring = "mytopic";
    len += MQTTSerialize_publish(buf + len, buflen - len, 0, 0, 0, 0, topicString, payload, payloadlen);

    len += MQTTSerialize_disconnect(buf + len, buflen - len);

    rc = Socket_new("", 1883, &mysock);
    rc = write(mysock, buf, len);
    rc = close(mysock);


use the official Paho MQTT client library. A simple example looks like the following:

    import org.eclipse.paho.client.mqttv3.MqttClient;
    import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
    import org.eclipse.paho.client.mqttv3.MqttException;
    import org.eclipse.paho.client.mqttv3.MqttMessage;
    import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

    public class MqttPublishSample {

        public static void main(String[] args) {

            String topic        = "MQTT Examples";
            String content      = "Message from MqttPublishSample";
            int qos             = 2;
            String broker       = "tcp://";
            String clientId     = "JavaSample";
            MemoryPersistence persistence = new MemoryPersistence();

            try {
                MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
                MqttConnectOptions connOpts = new MqttConnectOptions();
                System.out.println("Connecting to broker: "+broker);
                System.out.println("Publishing message: "+content);
                MqttMessage message = new MqttMessage(content.getBytes());
                sampleClient.publish(topic, message);
                System.out.println("Message published");
            } catch(MqttException me) {
                System.out.println("reason "+me.getReasonCode());
                System.out.println("msg "+me.getMessage());
                System.out.println("loc "+me.getLocalizedMessage());
                System.out.println("cause "+me.getCause());
                System.out.println("excep "+me);


use the mqtt_lua client library. The library requires A simple example looks like the following:

    -- Define a function which is called by mqtt_client:handler(),
    -- whenever messages are received on the subscribed topics

      function callback(topic, message)
        print("Received: " .. topic .. ": " .. message)
        if (message == "quit") then running = false end

    -- Create an MQTT client instance, connect to the MQTT server and
    -- subscribe to the topic called "test/2"

      MQTT = require("mqtt_library")
      mqtt_client = MQTT.client.create("localhost", nil, callback)
      mqtt_client:connect("lua mqtt client"))

    -- Continously invoke mqtt_client:handler() to process the MQTT protocol and
    -- handle any received messages.  Also, publish a message on topic "test/1"

      running = true

      while (running) do
        mqtt_client:publish("test/1", "test message")
        socket.sleep(1.0)  -- seconds


Use the official Paho MQTT client library. A simple example looks like the following:

    import paho.mqtt.client as mqtt

    # The callback for when the client receives a CONNACK response from the server.
    def on_connect(client, userdata, rc):
        print("Connected with result code "+str(rc))
        # Subscribing in on_connect() means that if we lose the connection and
        # reconnect then subscriptions will be renewed.

    # The callback for when a PUBLISH message is received from the server.
    def on_message(client, userdata, msg):
        print(msg.topic+" "+str(msg.payload))

    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message

    client.connect("", 1883, 60)

    # Blocking call that processes network traffic, dispatches callbacks and
    # handles reconnecting.
    # Other loop*() functions are available that give a threaded interface and a
    # manual interface.


Use the official Paho MQTT client library. This library is meant to be used in the web browser. It requires that VerneMQ has a websocket listener configured. A simple example for using the client on a webpage could look like the following:

    // Create a client instance
    client = new Paho.MQTT.Client(location.hostname, Number(location.port), "clientId");

    // set callback handlers
    client.onConnectionLost = onConnectionLost;
    client.onMessageArrived = onMessageArrived;

    // connect the client

    // called when the client connects
    function onConnect() {
      // Once a connection has been made, make a subscription and send a message.
      message = new Paho.MQTT.Message("Hello");
      message.destinationName = "/World";

    // called when the client loses its connection
    function onConnectionLost(responseObject) {
      if (responseObject.errorCode !== 0) {

    // called when a message arrives
    function onMessageArrived(message) {


In principle it is possible to use the Paho Java library directly for this, but a much better option is to use Paho Android Client and Service which wraps the java library in an Android Service which makes it easy to send and receive messages on behalf of Android applications, even when they are not currently running.


In principle it is possible to wrap a C library and get it to work on iOS, but since Apple does not permit third party networking stacks access to the mobile antenna we recommend the native Objective-C MQTT-Client-Framework.


Use the knolleary MQTT client library. The library requires the Arduino Ethernet Shield. A simple example looks like the following:

    #include <SPI.h>
    #include <Ethernet.h>
    #include <PubSubClient.h>

    // Update these with values suitable for your network.
    byte mac[]    = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
    byte server[] = { 172, 16, 0, 2 };
    byte ip[]     = { 172, 16, 0, 100 };

    void callback(char* topic, byte* payload, unsigned int length) {
      // handle message arrived

    EthernetClient ethClient;
    PubSubClient client(server, 1883, callback, ethClient);

    void setup()
      Ethernet.begin(mac, ip);
      if (client.connect("arduinoClient")) {
        client.publish("outTopic","hello world");

    void loop()

Above mentioned Libraries based on recommendation according to official VerneMQ Docs. Sometimes I used with different Libraries but use recommended libreries for better experience and seamless output.

I hope you like this post “ Connecting to VerneMQ ”. Do you have any questions? Leave a comment down below!

Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing my blog.

Harshvardhan Mishra

Hi, I'm Harshvardhan Mishra. Tech enthusiast and IT professional with a B.Tech in IT, PG Diploma in IoT from CDAC, and 6 years of industry experience. Founder of HVM Smart Solutions, blending technology for real-world solutions. As a passionate technical author, I simplify complex concepts for diverse audiences. Let's connect and explore the tech world together! If you want to help support me on my journey, consider sharing my articles, or Buy me a Coffee! Thank you for reading my blog! Happy learning! Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *