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.

109 lines
2.1 KiB

7 years ago
  1. /**
  2. * Module dependencies.
  3. */
  4. var url = require('./url');
  5. var parser = require('socket.io-parser');
  6. var Manager = require('./manager');
  7. var debug = require('debug')('socket.io-client');
  8. /**
  9. * Module exports.
  10. */
  11. module.exports = exports = lookup;
  12. /**
  13. * Managers cache.
  14. */
  15. var cache = exports.managers = {};
  16. /**
  17. * Looks up an existing `Manager` for multiplexing.
  18. * If the user summons:
  19. *
  20. * `io('http://localhost/a');`
  21. * `io('http://localhost/b');`
  22. *
  23. * We reuse the existing instance based on same scheme/port/host,
  24. * and we initialize sockets for each namespace.
  25. *
  26. * @api public
  27. */
  28. function lookup (uri, opts) {
  29. if (typeof uri === 'object') {
  30. opts = uri;
  31. uri = undefined;
  32. }
  33. opts = opts || {};
  34. var parsed = url(uri);
  35. var source = parsed.source;
  36. var id = parsed.id;
  37. var path = parsed.path;
  38. var sameNamespace = cache[id] && path in cache[id].nsps;
  39. var newConnection = opts.forceNew || opts['force new connection'] ||
  40. false === opts.multiplex || sameNamespace;
  41. var io;
  42. if (newConnection) {
  43. debug('ignoring socket cache for %s', source);
  44. io = Manager(source, opts);
  45. } else {
  46. if (!cache[id]) {
  47. debug('new io instance for %s', source);
  48. cache[id] = Manager(source, opts);
  49. }
  50. io = cache[id];
  51. }
  52. if (parsed.query && !opts.query) {
  53. opts.query = parsed.query;
  54. } else if (opts && 'object' === typeof opts.query) {
  55. opts.query = encodeQueryString(opts.query);
  56. }
  57. return io.socket(parsed.path, opts);
  58. }
  59. /**
  60. * Helper method to parse query objects to string.
  61. * @param {object} query
  62. * @returns {string}
  63. */
  64. function encodeQueryString (obj) {
  65. var str = [];
  66. for (var p in obj) {
  67. if (obj.hasOwnProperty(p)) {
  68. str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
  69. }
  70. }
  71. return str.join('&');
  72. }
  73. /**
  74. * Protocol version.
  75. *
  76. * @api public
  77. */
  78. exports.protocol = parser.protocol;
  79. /**
  80. * `connect`.
  81. *
  82. * @param {String} uri
  83. * @api public
  84. */
  85. exports.connect = lookup;
  86. /**
  87. * Expose constructors for standalone build.
  88. *
  89. * @api public
  90. */
  91. exports.Manager = require('./manager');
  92. exports.Socket = require('./socket');