index.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. return io.socket(parsed.path);
  53. }
  54. /**
  55. * Protocol version.
  56. *
  57. * @api public
  58. */
  59. exports.protocol = parser.protocol;
  60. /**
  61. * `connect`.
  62. *
  63. * @param {String} uri
  64. * @api public
  65. */
  66. exports.connect = lookup;
  67. /**
  68. * Expose constructors for standalone build.
  69. *
  70. * @api public
  71. */
  72. exports.Manager = require('./manager');
  73. exports.Socket = require('./socket');