Matteo Collina edited this page Nov 21, 2013 · 13 revisions

Client API


The primary method of instantiating MqttClient is through the factory method mqtt.createClient or mqtt.createSecureClient for a tls secured client.

It is possible to instantiate MqttClient using new MqttClient(...), but it requires the user to generate their own underlying stream (such as a net.Socket). Thus, it is recommended that the factory methods be used


The MqttClient class represents a client connection to an MQTT broker over an arbitrary transport method (TCP, UDP, TLS etc.). It makes heavy use of MqttConnection (see: MqttConnection).

MqttClient automatically handles the following:

  • Regular server pings
  • QoS flow
  • Default arguments to MqttConnection methods

MqttClient(streamBuilder, [options])

Instantiate a new instance of MqttClient

  • streamBuilder is a function that returns a subclass of the Stream class that supports the connect event. Typically a net.Socket.
  • options is the client connection options (see: MqttConnection#connect). Defaults:
    • keepalive: 10
    • clientId: 'mqttjs'_ + crypto.randomBytes(16).toString('hex')
    • protocolId: 'MQIsdp'
    • protocolVersion: 3
    • encoding: 'utf8' (set to 'binary' for receiving binary payloads)

MqttClient#publish(topic, message, [options], [callback])

Publish a message

  • topic is the topic to publish to, String
  • message is the message to publish, Buffer or String
  • options is the options to publish with, including:
    • qos qos level
    • retain retain flag
  • callback callback fired when the QoS handling completes

MqttClient#subscribe(topic, [options], [callback])

Subscribe to a topic or topics

  • topic is a String topic to subscribe to or an Array of topics to subscribe to.
  • options is the options to subscribe with, including:
    • qos qos subscription level
  • callback - function(err, granted) callback fired on suback where:
    • err a subscription error
    • granted is an array of {topic, qos} where:
      • topic is a subscribed to topic
      • qos is the granted qos level on it

MqttClient#unsubscribe(topic, [callback])

Unsubscribe from a topic or topics

  • topic is a String topic or an array of topics to unsubscribe from
  • callback fired on unsuback


Close connection - send a disconnect packet and close the underlying stream

Event 'connect'

function() {}
Emitted on successful connection (i.e. connack rc=0)

Event 'message'

function(topic, message, packet) {}
Emitted when the client recieves a publish packet

  • topic topic of the received packet
  • message payload of the received packet
  • packet received packet, as used in MqttConnection