server.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict'
  2. var Server = require('../server')
  3. var fs = require('fs')
  4. module.exports.init_server = function (PORT) {
  5. var server = new Server(function (client) {
  6. client.on('connect', function () {
  7. client.connack(0)
  8. })
  9. client.on('publish', function (packet) {
  10. switch (packet.qos) {
  11. case 1:
  12. client.puback({messageId: packet.messageId})
  13. break
  14. case 2:
  15. client.pubrec({messageId: packet.messageId})
  16. break
  17. default:
  18. break
  19. }
  20. })
  21. client.on('pubrel', function (packet) {
  22. client.pubcomp({messageId: packet.messageId})
  23. })
  24. client.on('pingreq', function () {
  25. client.pingresp()
  26. })
  27. client.on('disconnect', function () {
  28. client.stream.end()
  29. })
  30. })
  31. server.listen(PORT)
  32. return server
  33. }
  34. module.exports.init_secure_server = function (port, key, cert) {
  35. var server = new Server.SecureServer({
  36. key: fs.readFileSync(key),
  37. cert: fs.readFileSync(cert)
  38. }, function (client) {
  39. client.on('connect', function () {
  40. client.connack({returnCode: 0})
  41. })
  42. })
  43. server.listen(port)
  44. return server
  45. }