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.

89 lines
2.2 KiB

4 years ago
  1. 'use strict';
  2. var EventEmitter = require('events').EventEmitter
  3. , inherits = require('inherits')
  4. , urlUtils = require('./utils/url')
  5. , XDR = require('./transport/sender/xdr')
  6. , XHRCors = require('./transport/sender/xhr-cors')
  7. , XHRLocal = require('./transport/sender/xhr-local')
  8. , XHRFake = require('./transport/sender/xhr-fake')
  9. , InfoIframe = require('./info-iframe')
  10. , InfoAjax = require('./info-ajax')
  11. ;
  12. var debug = function() {};
  13. if (process.env.NODE_ENV !== 'production') {
  14. debug = require('debug')('sockjs-client:info-receiver');
  15. }
  16. function InfoReceiver(baseUrl, urlInfo) {
  17. debug(baseUrl);
  18. var self = this;
  19. EventEmitter.call(this);
  20. setTimeout(function() {
  21. self.doXhr(baseUrl, urlInfo);
  22. }, 0);
  23. }
  24. inherits(InfoReceiver, EventEmitter);
  25. // TODO this is currently ignoring the list of available transports and the whitelist
  26. InfoReceiver._getReceiver = function(baseUrl, url, urlInfo) {
  27. // determine method of CORS support (if needed)
  28. if (urlInfo.sameOrigin) {
  29. return new InfoAjax(url, XHRLocal);
  30. }
  31. if (XHRCors.enabled) {
  32. return new InfoAjax(url, XHRCors);
  33. }
  34. if (XDR.enabled && urlInfo.sameScheme) {
  35. return new InfoAjax(url, XDR);
  36. }
  37. if (InfoIframe.enabled()) {
  38. return new InfoIframe(baseUrl, url);
  39. }
  40. return new InfoAjax(url, XHRFake);
  41. };
  42. InfoReceiver.prototype.doXhr = function(baseUrl, urlInfo) {
  43. var self = this
  44. , url = urlUtils.addPath(baseUrl, '/info')
  45. ;
  46. debug('doXhr', url);
  47. this.xo = InfoReceiver._getReceiver(baseUrl, url, urlInfo);
  48. this.timeoutRef = setTimeout(function() {
  49. debug('timeout');
  50. self._cleanup(false);
  51. self.emit('finish');
  52. }, InfoReceiver.timeout);
  53. this.xo.once('finish', function(info, rtt) {
  54. debug('finish', info, rtt);
  55. self._cleanup(true);
  56. self.emit('finish', info, rtt);
  57. });
  58. };
  59. InfoReceiver.prototype._cleanup = function(wasClean) {
  60. debug('_cleanup');
  61. clearTimeout(this.timeoutRef);
  62. this.timeoutRef = null;
  63. if (!wasClean && this.xo) {
  64. this.xo.close();
  65. }
  66. this.xo = null;
  67. };
  68. InfoReceiver.prototype.close = function() {
  69. debug('close');
  70. this.removeAllListeners();
  71. this._cleanup(false);
  72. };
  73. InfoReceiver.timeout = 8000;
  74. module.exports = InfoReceiver;