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