Skip to main content

Overview

Connecting clients to your MQTT broker is the first step in building IoT applications. This guide demonstrates how to establish connections to HiveMQ Community Edition using popular MQTT client libraries across different programming languages.
HiveMQ Community Edition runs on port 1883 for standard MQTT and port 8883 for MQTT over TLS by default.

Connection Basics

Every MQTT connection requires:
  • Broker address: The hostname or IP address of your HiveMQ broker
  • Port: 1883 (TCP) or 8883 (TLS)
  • Client ID: A unique identifier for the client (auto-generated if not specified)
  • Clean Session: Whether to persist session state (true/false)
  • Credentials: Username and password (optional, depending on configuration)

Client Examples

Python (Paho MQTT)

The Eclipse Paho Python client is one of the most popular MQTT libraries.
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected successfully to HiveMQ")
    else:
        print(f"Connection failed with code {rc}")

def on_disconnect(client, userdata, rc):
    if rc != 0:
        print("Unexpected disconnection")

# Create client instance
client = mqtt.Client(client_id="python_client_001")

# Assign callbacks
client.on_connect = on_connect
client.on_disconnect = on_disconnect

# Connect to HiveMQ
client.connect("localhost", 1883, 60)

# Start network loop
client.loop_forever()
Install Paho MQTT with: pip install paho-mqtt

JavaScript (MQTT.js)

MQTT.js works in both Node.js and browser environments.
const mqtt = require('mqtt');

const client = mqtt.connect('mqtt://localhost:1883', {
  clientId: 'nodejs_client_001',
  clean: true,
  connectTimeout: 4000,
  reconnectPeriod: 1000,
});

client.on('connect', () => {
  console.log('Connected to HiveMQ');
});

client.on('error', (error) => {
  console.error('Connection error:', error);
});

client.on('disconnect', () => {
  console.log('Disconnected from broker');
});
Install MQTT.js with: npm install mqtt

Java (HiveMQ Client)

The HiveMQ MQTT Client is a modern, high-performance Java library.
import com.hivemq.client.mqtt.mqtt3.Mqtt3BlockingClient;
import com.hivemq.client.mqtt.mqtt3.Mqtt3Client;

public class HiveMQConnect {
    public static void main(String[] args) {
        Mqtt3BlockingClient client = Mqtt3Client.builder()
                .identifier("java_client_001")
                .serverHost("localhost")
                .serverPort(1883)
                .buildBlocking();

        client.connect();
        System.out.println("Connected to HiveMQ");

        // Keep application running
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            client.disconnect();
            System.out.println("Disconnected");
        }));
    }
}

Mosquitto CLI

The Mosquitto command-line tools provide quick testing capabilities.
# Basic subscribe
mosquitto_sub -h localhost -p 1883 -t "sensors/#" -v

# With authentication
mosquitto_sub -h localhost -p 1883 -t "sensors/temp" -u admin -P hivemq

# With client ID
mosquitto_sub -h localhost -p 1883 -t "devices/+" -i "cli_subscriber" -v

Connection Parameters

Clean Session (MQTT 3.1.1) or Clean Start (MQTT 5.0) determines session persistence:
  • true: Broker discards previous session state
  • false: Broker stores subscriptions and queued messages
# MQTT 3.1.1
client = mqtt.Client(clean_session=True)

# MQTT 5.0
client = mqtt.Client(protocol=mqtt.MQTTv5, clean_start=True)

Connection Troubleshooting

Common connection issues:
  • Connection refused: Check if HiveMQ is running and the port is correct
  • Authentication failed: Verify username/password in HiveMQ configuration
  • Timeout: Check firewall rules and network connectivity
  • Client ID already in use: Ensure unique client IDs or enable clean session

Verify Broker Status

# Check if HiveMQ is running
docker ps | grep hivemq

# Check broker logs
docker logs hivemq-ce

# Test connectivity
telnet localhost 1883

Best Practices

  1. Use unique Client IDs: Prevent unexpected disconnections
  2. Implement reconnection logic: Handle network interruptions gracefully
  3. Set appropriate timeouts: Balance responsiveness and network conditions
  4. Handle connection callbacks: Monitor connection state changes
  5. Use TLS in production: Encrypt data in transit
  6. Configure keep-alive properly: Optimize for your network latency

Next Steps

Publishing & Subscribing

Learn how to exchange messages between clients

Quality of Service

Understand QoS levels for reliable messaging

Build docs developers (and LLMs) love