UNPKG

1.05 kBJavaScriptView Raw
1'use strict'
2
3var mqtt = require('mqtt')
4
5var clientId = 'mqttjs_' + Math.random().toString(16).substr(2, 8)
6
7var host = 'wss://localhost:3001/Mosca'
8
9var options = {
10 keepalive: 10,
11 clientId: clientId,
12 protocolId: 'MQTT',
13 protocolVersion: 4,
14 clean: true,
15 reconnectPeriod: 1000,
16 connectTimeout: 30 * 1000,
17 will: {
18 topic: 'WillMsg',
19 payload: 'Connection Closed abnormally..!',
20 qos: 0,
21 retain: false
22 },
23 username: 'demo',
24 password: 'demo',
25 rejectUnauthorized: false
26}
27
28var client = mqtt.connect(host, options)
29
30client.on('error', function (err) {
31 console.log(err)
32 client.end()
33})
34
35client.on('connect', function () {
36 console.log('client connected:' + clientId)
37})
38
39client.subscribe('topic', { qos: 0 })
40
41client.publish('topic', 'wss secure connection demo...!', { qos: 0, retain: false })
42
43client.on('message', function (topic, message, packet) {
44 console.log('Received Message:= ' + message.toString() + '\nOn topic:= ' + topic)
45})
46
47client.on('close', function () {
48 console.log(clientId + ' disconnected')
49})