client.js 1.0 KB

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