I am trying to understand how the Javascript client code of socket.io works. Specifically, my goal is to understand, how does it know where the server is located?
The client code I use in my program is very simple – I just link to socket.io.js:
<script src="./socket.io/socket.io.js"></script>
and then:
var socket = io.connect()
And that’s it – the socket automatically connects to the server. But how does it know?
I looked at socket.io.js, and this is what I found (comments trimmed):
var io = ('undefined' === typeof module ? {} : module.exports);
(function() {
/** Copyright(c) 2011 LearnBoost <dev@learnboost.com> * MIT Licensed */
(function (exports, global) {
var io = exports;
io.version = '0.9.11';
io.protocol = 1;
io.transports = [];
io.j = [];
io.sockets = {};
/**
* Manages connections to hosts.
* @param {String} uri
* @Param {Boolean} force creation of new socket (defaults to false)
* @api public
*/
io.connect = function (host, details) {
var uri = io.util.parseUri(host)
, uuri
, socket;
if (global && global.location) {
uri.protocol = uri.protocol || global.location.protocol.slice(0, -1);
uri.host = uri.host || (global.document
? global.document.domain : global.location.hostname);
uri.port = uri.port || global.location.port;
}
uuri = io.util.uniqueUri(uri);
...
})('object' === typeof module ? module.exports : (this.io = {}), this);
...
})();
It seems the secret is in the “global” param, but, who exactly sends “global” to this function? (it’s difficult to understand the functions with all the parentheses…)
the pattern youre looking for is this:
thisreference is the scope in which this function is executed (this pattern both defines the function and executes it), which happens to be the global scope. for more information about javascript scopes see here – http://tore.darell.no/pages/scope_in_javascript