mqttclient.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict'
  2. /** ************************** IMPORTANT NOTE ***********************************
  3. The certificate used on this example has been generated for a host named stark.
  4. So as host we SHOULD use stark if we want the server to be authorized.
  5. For testing this we should add on the computer running this example a line on
  6. the hosts file:
  7. /etc/hosts [UNIX]
  8. OR
  9. \System32\drivers\etc\hosts [Windows]
  10. The line to add on the file should be as follows:
  11. <the ip address of the server> stark
  12. *******************************************************************************/
  13. var mqtt = require('mqtt')
  14. var fs = require('fs')
  15. var path = require('path')
  16. var KEY = fs.readFileSync(path.join(__dirname, '/tls-key.pem'))
  17. var CERT = fs.readFileSync(path.join(__dirname, '/tls-cert.pem'))
  18. var TRUSTED_CA_LIST = fs.readFileSync(path.join(__dirname, '/crt.ca.cg.pem'))
  19. var PORT = 1883
  20. var HOST = 'stark'
  21. var options = {
  22. port: PORT,
  23. host: HOST,
  24. key: KEY,
  25. cert: CERT,
  26. rejectUnauthorized: true,
  27. // The CA list will be used to determine if server is authorized
  28. ca: TRUSTED_CA_LIST,
  29. protocol: 'mqtts'
  30. }
  31. var client = mqtt.connect(options)
  32. client.subscribe('messages')
  33. client.publish('messages', 'Current time is: ' + new Date())
  34. client.on('message', function (topic, message) {
  35. console.log(message)
  36. })
  37. client.on('connect', function () {
  38. console.log('Connected')
  39. })