a479e3cfee88223fb38c8d17c72ecc495e4de9f2a679652a23ce8364795d693dfe3025831b49d9a0a4a0cccfcce3d88a7812c2439455232b26f84cff52e623 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. var inherits = require('inherits')
  3. , EventEmitter = require('events').EventEmitter
  4. ;
  5. var debug = function() {};
  6. if (process.env.NODE_ENV !== 'production') {
  7. debug = require('debug')('sockjs-client:polling');
  8. }
  9. function Polling(Receiver, receiveUrl, AjaxObject) {
  10. debug(receiveUrl);
  11. EventEmitter.call(this);
  12. this.Receiver = Receiver;
  13. this.receiveUrl = receiveUrl;
  14. this.AjaxObject = AjaxObject;
  15. this._scheduleReceiver();
  16. }
  17. inherits(Polling, EventEmitter);
  18. Polling.prototype._scheduleReceiver = function() {
  19. debug('_scheduleReceiver');
  20. var self = this;
  21. var poll = this.poll = new this.Receiver(this.receiveUrl, this.AjaxObject);
  22. poll.on('message', function(msg) {
  23. debug('message', msg);
  24. self.emit('message', msg);
  25. });
  26. poll.once('close', function(code, reason) {
  27. debug('close', code, reason, self.pollIsClosing);
  28. self.poll = poll = null;
  29. if (!self.pollIsClosing) {
  30. if (reason === 'network') {
  31. self._scheduleReceiver();
  32. } else {
  33. self.emit('close', code || 1006, reason);
  34. self.removeAllListeners();
  35. }
  36. }
  37. });
  38. };
  39. Polling.prototype.abort = function() {
  40. debug('abort');
  41. this.removeAllListeners();
  42. this.pollIsClosing = true;
  43. if (this.poll) {
  44. this.poll.abort();
  45. }
  46. };
  47. module.exports = Polling;