client - mqttjs/MQTT.js GitHub Wiki
Client API
Introduction
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
MqttClient
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
MqttConnectionmethods
MqttClient(streamBuilder, [options])
Instantiate a new instance of MqttClient
streamBuilderis a function that returns a subclass of theStreamclass that supports theconnectevent. Typically anet.Socket.optionsis the client connection options (see: MqttConnection#connect). Defaults:keepalive:10clientId:'mqttjs'_ + crypto.randomBytes(16).toString('hex')protocolId:'MQIsdp'protocolVersion:3encoding:'utf8'(set to'binary'for receiving binary payloads)
MqttClient#publish(topic, message, [options], [callback])
Publish a message
topicis the topic to publish to,Stringmessageis the message to publish,BufferorStringoptionsis the options to publish with, including:qosqos levelretainretain flag
callbackcallback fired when the QoS handling completes
MqttClient#subscribe(topic, [options], [callback])
Subscribe to a topic or topics
topicis aStringtopic to subscribe to or anArrayof topics to subscribe to.optionsis the options to subscribe with, including:qosqos subscription level
callback-function(err, granted)callback fired on suback where:erra subscription errorgrantedis an array of{topic, qos}where:topicis a subscribed to topicqosis the granted qos level on it
MqttClient#unsubscribe(topic, [callback])
Unsubscribe from a topic or topics
topicis aStringtopic or an array of topics to unsubscribe fromcallbackfired on unsuback
MqttClient#end()
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
topictopic of the received packetmessagepayload of the received packetpacketreceived packet, as used in MqttConnection