Error connecting esp32 to mqtt broker

Hi!

I'm a noob to Arduino, coding, and MQTT etc.

Trying to send "Hello World" to MQTTX to validate it's connection

"Attempting MQTT connection...failed, state = -2 "

When I simulated via Wowki, it was able to connect to MQTTX

what's wrong in the code and how can it be resolved?

Any help is appreciated.

#include <WiFi.h>
#include <Wire.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>

const char* ssid = "YourWiFi";
const char* password = "YourPassword";

//MQTT Broker Config
const char* mqtt_broker = "broker.emqx.io";
const char* topic = "customtopicname";
const char* mqtt_username = "customusername";
const char* mqtt_password = "custompassword";
const int   mqtt_port = 1883;

String stMac;
char mac[50];
String ip;

WiFiServer server(80);

WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);

// searches and connects to WiFi access point specified in variable declaration
void initWiFi() 
{

    delay(10);
    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("");
    Serial.println("WiFi connected.");
    Serial.println("IP address: ");
    ip = WiFi.localIP().toString();
    Serial.println(ip);
    Serial.println(WiFi.macAddress());
    stMac = WiFi.macAddress();
    stMac.replace(":", "_");
    Serial.println(stMac);

    server.begin();
}

// connection to MQTT server
void mqttConnect()
{
    mqttClient.setServer(mqtt_broker, mqtt_port);
    while (!mqttClient.connected())
    {
        Serial.printf("The client %s connects to the public MQTT broker\n", "mqttx_cbb540d9");
        if (mqttClient.connect("custom_client_id_name", mqtt_username, mqtt_password))
        {
            Serial.println("Public EMQX MQTT broker connected");
        }
        else
        {
            Serial.print("failed with state ");
            Serial.println(mqttClient.state());
            delay(5000);
        }
    }
}

// the setup function runs once when you press reset or power the board
void setup() 
{
    Serial.begin(115200);
    initWiFi();
}

// the loop function runs over and over again until power down or reset
void loop() 
{
    if (!mqttClient.connected())
    {
        mqttConnect();
    }
    mqttClient.loop();

    //MQTT Server 
    mqttClient.publish(topic, "Hello world", true);

}
End Code