server.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. 'use strict'
  2. var net = require('net')
  3. var tls = require('tls')
  4. var inherits = require('inherits')
  5. var Connection = require('mqtt-connection')
  6. var MqttServer
  7. var FastMqttServer
  8. var MqttSecureServer
  9. function setupConnection (duplex) {
  10. var that = this
  11. var connection = new Connection(duplex, function () {
  12. that.emit('client', connection)
  13. })
  14. }
  15. /*
  16. * MqttServer
  17. *
  18. * @param {Function} listener - fired on client connection
  19. */
  20. MqttServer = module.exports = function Server (listener) {
  21. if (!(this instanceof Server)) {
  22. return new Server(listener)
  23. }
  24. net.Server.call(this)
  25. this.on('connection', setupConnection)
  26. if (listener) {
  27. this.on('client', listener)
  28. }
  29. return this
  30. }
  31. inherits(MqttServer, net.Server)
  32. /*
  33. * FastMqttServer(w/o waiting for initialization)
  34. *
  35. * @param {Function} listener - fired on client connection
  36. */
  37. FastMqttServer = module.exports.FastMqttServer = function Server (listener) {
  38. if (!(this instanceof Server)) {
  39. return new Server(listener)
  40. }
  41. net.Server.call(this)
  42. this.on('connection', function (duplex) {
  43. var connection = new Connection(duplex)
  44. this.emit('client', connection)
  45. })
  46. if (listener) {
  47. this.on('client', listener)
  48. }
  49. return this
  50. }
  51. inherits(FastMqttServer, net.Server)
  52. /**
  53. * MqttSecureServer
  54. *
  55. * @param {Object} opts - server options
  56. * @param {Function} listener
  57. */
  58. MqttSecureServer = module.exports.SecureServer =
  59. function SecureServer (opts, listener) {
  60. if (!(this instanceof SecureServer)) {
  61. return new SecureServer(opts, listener)
  62. }
  63. // new MqttSecureServer(function(){})
  64. if (typeof opts === 'function') {
  65. listener = opts
  66. opts = {}
  67. }
  68. tls.Server.call(this, opts)
  69. if (listener) {
  70. this.on('client', listener)
  71. }
  72. this.on('secureConnection', setupConnection)
  73. return this
  74. }
  75. inherits(MqttSecureServer, tls.Server)