You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.5 KiB

4 years ago
  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:receiver:xhr');
  8. }
  9. function XhrReceiver(url, AjaxObject) {
  10. debug(url);
  11. EventEmitter.call(this);
  12. var self = this;
  13. this.bufferPosition = 0;
  14. this.xo = new AjaxObject('POST', url, null);
  15. this.xo.on('chunk', this._chunkHandler.bind(this));
  16. this.xo.once('finish', function(status, text) {
  17. debug('finish', status, text);
  18. self._chunkHandler(status, text);
  19. self.xo = null;
  20. var reason = status === 200 ? 'network' : 'permanent';
  21. debug('close', reason);
  22. self.emit('close', null, reason);
  23. self._cleanup();
  24. });
  25. }
  26. inherits(XhrReceiver, EventEmitter);
  27. XhrReceiver.prototype._chunkHandler = function(status, text) {
  28. debug('_chunkHandler', status);
  29. if (status !== 200 || !text) {
  30. return;
  31. }
  32. for (var idx = -1; ; this.bufferPosition += idx + 1) {
  33. var buf = text.slice(this.bufferPosition);
  34. idx = buf.indexOf('\n');
  35. if (idx === -1) {
  36. break;
  37. }
  38. var msg = buf.slice(0, idx);
  39. if (msg) {
  40. debug('message', msg);
  41. this.emit('message', msg);
  42. }
  43. }
  44. };
  45. XhrReceiver.prototype._cleanup = function() {
  46. debug('_cleanup');
  47. this.removeAllListeners();
  48. };
  49. XhrReceiver.prototype.abort = function() {
  50. debug('abort');
  51. if (this.xo) {
  52. this.xo.close();
  53. debug('close');
  54. this.emit('close', null, 'user');
  55. this.xo = null;
  56. }
  57. this._cleanup();
  58. };
  59. module.exports = XhrReceiver;