title: Node.js & Socket.io with multiple tabs
body: <p>From my understanding, a socket.io server manages N connections between itself and N clients via N separate sockets, each with its own ID.</p>
  
  <p>It therefore makes sense that you get two different ID's when opening two tabs.</p>
  
  <p>Consider, however, this minimal example:</p>
  
  <p><strong>index.html</strong></p>
  
  <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
  &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;&lt;/html&gt;
  &lt;head&gt;
      &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"&gt;&lt;/script&gt;
      &lt;title&gt;Stuffy Stuff&lt;/title&gt;
  &lt;/head&gt;
  
  &lt;body&gt;
      &lt;button id="btnA"&gt;A&lt;/button&gt;
  
      &lt;script src="/socket.io/socket.io.js"&gt;&lt;/script&gt;
      &lt;script src="app.js"&gt;&lt;/script&gt;
  &lt;/body&gt;
  </code></pre>
  
  <p><strong>index.js</strong></p>
  
  <pre><code>var express = require('express');
  var path = require('path');
  var app = express();
  var servercode = require('./server');
  
  app.use(express.static(path.join(__dirname,'public')));
  
  var server = require('http').createServer(app).listen(process.env.PORT || 8080);
  var io = require('socket.io').listen(server);
  
  io.on('connection', function (socket)
  {
      console.log('client ' + socket.id + ' connected');
      servercode.init(io, socket);
  });
  </code></pre>
  
  <p><strong>app.js</strong></p>
  
  <pre><code>;
  jQuery(function($) // client-side code
  {
      socket = io.connect();
  
      $(document).on('click', '#btnA', stuff);
  
      function stuff()
      {
          socket.emit('dostuff', socket.id);
          socket.on('answerstuff', function()
          {
              console.log("Answered");
          });
      }
  }($));
  </code></pre>
  
  <p><strong>server.js</strong></p>
  
  <pre><code>// Server-side
  
  var io;
  var socket;
  
  exports.init = function(sio, sock)
  {
      io = sio;
      socket = sock;
  
      socket.on('dostuff', doStuff);
  };
  
  function doStuff(idd)
  {
      console.log('who is asking: ' + idd);
      console.log('who am I answering to: ' + socket.id);  
      console.log(socket.id);
      socket.emit('answerstuff');
  }
  </code></pre>
  
  <p>Now say I fire up <code>node index.js</code> and then open two instances of <code>localhost:8080</code>; let's call them A and B. If I press the button on A's instance, the 'dostuff' message is emitted, it's caught by the server, <em>but the socket it answers to is the one relative to B's instance</em>, not A's. In general, it answers to the most recent instance. Why is it so?</p>
  
  <p><strong>EDIT: explanation</strong>
  As I've finally grasped the nature of my mistake I thought I could help whoever runs into a similar issue.</p>
  
  <p>Let's take our sample workflow: A connects, B connects, A presses button.</p>
  
  <ol>
  <li><code>server.init(io, socket A)</code> gets called</li>
  <li><code>init(socket A)</code> attaches the <code>dostuff</code> event, with callback function <code>doStuff</code>, to socket A</li>
  <li>B connects... <code>init</code> attaches <code>dostuff</code> to socket B</li>
  <li>Client A presses button, thus A emits <code>dostuff</code> passing socket A's id</li>
  <li><code>doStuff(idd)</code> is executed, but its definition contains a reference to a variable (<code>socket</code>) not defined within the function's scope, therefore it has to navigate its parent scopes</li>
  <li>Such reference is found: it's <code>socket = sock</code> (if we omit <code>var</code>, the declaration 'bubbles up' in scope until it finds a variable with such a name. Had we written <code>var socket = sock</code> INSIDE <code>init</code>, the function couldn't have found any such variable)
  
  <ol start="7">
  <li>But <code>socket</code> points to socket B thanks to B connecting and <code>init</code> being executed again. Therefore, the function only knows socket B.</li>
  </ol></li>
  </ol>
  
  <p>In order to solve this issue we need to employ <em>closures</em>: functions that encapsulate the state of the world at the moment of their definition. In other words, a closure is an object containing the function definition AND the value of the variables not in the function scope but referenced by it.</p>
  
  <p>As illustrated in the solution given by JagsSparrow, there are two ways of dealing with this issue and both involve creating a closure:</p>
  
  <p><strong>1. Use the <code>function.bind(thisArg, args)</code> function</strong></p>
  
  <p>The <code>bind()</code> function returns the function 'A' it's called upon where <code>this</code> is bound to <code>thisArg</code> (where it would normally point to the object calling A) and instantiates whatever arguments are specified in <code>args</code>.</p>
  
  <p>In our case we don't need <code>this</code> as it's never mentioned in the <code>doStuff()</code> function, but we do need it to remember whose socket is the one mentioned in the arguments. We can do this by writing</p>
  
  <pre><code>doStuff.bind(null, socket)
  </code></pre>
  
  <p>This expression returns an object that is the <code>doStuff()</code> function where, in its context, <code>this</code> equals <code>null</code> (we could've written <code>doStuff.bind(this, socket)</code>: in that case, <code>this</code> equals <code>init</code>) and its first argument, <code>socket</code>, is bound to <code>socket</code>. Therefore,</p>
  
  <pre><code>socket.on('dostuff', doStuff.bind(this,socket));
  </code></pre>
  
  <p>tells socket A to fire up <code>doStuff</code> (which <em>contains a reference to socket A</em>) when <code>dostuff</code> happens. Same with socket B and any other socket.</p>
  
  <p><strong>2. Use a nested function</strong></p>
  
  <p>We simply move the definition of <code>function doStuff(idd)</code> inside <code>socket.on()</code>:</p>
  
  <pre><code>socket.on('dostuff', function doStuff(idd)
  {
      console.log('who is asking: ' + idd);
      console.log('who am I answering to: ' + socket.id);  
      console.log(socket.id);
      socket.emit('answerstuff');
  });
  </code></pre>
  
  <p>This way, again, the socket is bound to a function that contains (by virtue of the closure) the definition of whichever socket is performing this operation.</p>