Skip to content
Adam Rudd edited this page Feb 28, 2013 · 5 revisions

Server API

Introduction

The primary methods of instantiating mqtt.js server classes are through the mqtt.createServer and mqtt.createSecureServer methods. The former returns an instance of MqttServer and and the latter returns an instance of MqttSecureServer.

While it is possible to instantiate these classes through new MqttServer(), it is strongly recommended to use the factory methods.

Example

var mqtt = require('mqtt');
var server = mqtt.createServer(function(client) {
  client.on('connect', function(packet) {
    // Check if connect fields are correct
    // Add client to list of connected clients
    client.connack({returnCode: 0});
  });
  client.on('publish', function(packet) {
    // Perform QoS handling if necessary
    // Publish message to all appropriate clients
  });
  client.on('subscribe', function(packet) {
    // Add subscription to client subscription list
    client.suback([0]);
  });
  client.on('pingreq', function(packet) {
    client.pingresp();
  });
  client.on('disconnect', function(packet) {
    // Disconnect client
    // Remove from list of clients
  });
});

SecureServer example

var mqtt = require('mqtt');
var server = mqtt.createSecureServer(
    __dirname + 'private-key.pem',
    __dirname + 'cert.pem',
    function(client) {
  client.on('connect', function(packet) {
    // Check if connect fields are correct
    // Add client to list of connected clients
    client.connack({returnCode: 0});
  });
  client.on('publish', function(packet) {
    // Perform QoS handling if necessary
    // Publish message to all appropriate clients
  });
  client.on('subscribe', function(packet) {
    // Add subscription to client subscription list
    client.suback([0]);
  });
  client.on('pingreq', function(packet) {
    client.pingresp();
  });
  client.on('disconnect', function(packet) {
    // Disconnect client
    // Remove from list of clients
  });
});

MqttServer

MqttServer is a subclass of net.Server and as such inherits all its events and methods. It has, in addition, the following methods and events:

MqttServer([listener])

Instantiate a new MQTT server.

  • listener is a callback that is fired on the client event

Event: 'client'

function(client) {}
Emitted when a new TCP connection is received. client is an instance of MqttServerClient, a wrapper of MqttConnection (see MqttConnection).

MqttSecureServer

MqttSecureServer is a subclass of tls.Server. It has the following events and methods:

MqttSecureServer(keyPath, certPath, [listener])

Instantiate a new tls secured MQTT server.

keyPath is a path to a private key file certPath is a path to the corresponding public certificate listener is a callback that is fired on client events

Event: 'client'

See above.