This is documentation for the next version of Grafana k6 documentation. For the latest stable release, go to the latest version.

Open source

Client

The Client class provides a high-level, event-driven interface for interacting with MQTT brokers. It supports both synchronous and asynchronous operations for connecting, subscribing, publishing, and unsubscribing.

Constructor

JavaScript
new Client(options)

Creates a new MQTT client instance.

Parameters

ParameterTypeDescription
optionsobjectOptional client configuration
options.client_idstringClient identifier (must be unique per broker connection). If not provided, the broker assigns one.
options.usernamestringUsername for broker authentication
options.passwordstringPassword for broker authentication
options.credentials_providerfunctionFunction returning {username, password} for dynamic authentication
options.willobjectLast Will and Testament message configuration
options.will.topicstringTopic for the will message
options.will.payloadstringPayload for the will message
options.will.qosnumberQoS level for the will message (0, 1, or 2)
options.will.retainbooleanWhether the will message should be retained
options.tagsobjectCustom tags for metrics (key-value pairs)

Properties

PropertyTypeDescription
connectedbooleanRead-only. Indicates if the client is currently connected to the broker.

QoS

Quality of Service enumeration for message delivery guarantees:

ValueNameDescription
0QoS.AtMostOnceFire and forget. Message delivered at most once, no acknowledgment.
1QoS.AtLeastOnceMessage delivered at least once, with acknowledgment.
2QoS.ExactlyOnceMessage delivered exactly once, guaranteed and duplicate-free.

Methods

MethodDescription
connect()Connect to an MQTT broker
reconnect()Reconnect to the broker using previous parameters
subscribe()Subscribe to one or more topics
subscribeAsync()Subscribe to topics asynchronously
unsubscribe()Unsubscribe from topics
unsubscribeAsync()Unsubscribe from topics asynchronously
publish()Publish a message to a topic
publishAsync()Publish a message asynchronously
on()Register event handlers
end()Disconnect from the broker
endAsync()Disconnect from the broker asynchronously

Example

Basic Usage

JavaScript
import { Client } from "k6/x/mqtt";

export default function () {
  const client = new Client()

  client.on("connect", () => {
    console.log("Connected to MQTT broker")
    client.subscribe("greeting")

    client.publish("greeting", "Hello MQTT!")
  })

  client.on("message", (topic, message) => {
    const str = String.fromCharCode.apply(null, new Uint8Array(message))
    console.info("topic:", topic, "message:", str)
    client.end()
  })

  client.on("end", () => {
    console.log("Disconnected from MQTT broker")
  })

  client.connect(__ENV["MQTT_BROKER_ADDRESS"] || "mqtt://broker.emqx.io:1883")
}