1 | 'use strict'
|
2 |
|
3 | var mqtt = require('mqtt')
|
4 |
|
5 | var clientId = 'mqttjs_' + Math.random().toString(16).substr(2, 8)
|
6 |
|
7 | var host = 'wss://localhost:3001/Mosca'
|
8 |
|
9 | var 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 |
|
28 | var client = mqtt.connect(host, options)
|
29 |
|
30 | client.on('error', function (err) {
|
31 | console.log(err)
|
32 | client.end()
|
33 | })
|
34 |
|
35 | client.on('connect', function () {
|
36 | console.log('client connected:' + clientId)
|
37 | })
|
38 |
|
39 | client.subscribe('topic', { qos: 0 })
|
40 |
|
41 | client.publish('topic', 'wss secure connection demo...!', { qos: 0, retain: false })
|
42 |
|
43 | client.on('message', function (topic, message, packet) {
|
44 | console.log('Received Message:= ' + message.toString() + '\nOn topic:= ' + topic)
|
45 | })
|
46 |
|
47 | client.on('close', function () {
|
48 | console.log(clientId + ' disconnected')
|
49 | })
|