-
Notifications
You must be signed in to change notification settings - Fork 1.4k
server
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.
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
});
});
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 is a subclass of net.Server
and as such inherits
all its events and methods. It has, in addition, the following
methods and events:
Instantiate a new MQTT server.
-
listener
is a callback that is fired on theclient
event
function(client) {}
Emitted when a new TCP connection is received. client
is an
instance of MqttServerClient
, a wrapper of MqttConnection
(see MqttConnection).
MqttSecureServer is a subclass of tls.Server
. It has
the following events and methods:
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
See above.