title: Socket.io with Express, emit not working within express route
body: <p>Either I have a fundamental misunderstanding of how socket.io works (highly likely), or I am just finding some bug that nobody knows about (nearly impossible).</p>
  
  <p>I've been trying to integrate express with socket.io. On the client side, everything works fine: user clicks button, event emits, everybody's happy.</p>
  
  <p>However, let's say I want to emit this event from within an express route before rendering a page. The event never seems to be emitted. From all the questions on this that I've looked at, I'm supposed to be able to simply plug my "io" instance into my app and then access it from within my routes.</p>
  
  <p>So this is my setup...</p>
  
  <p>// index.js</p>
  
  <pre><code>var app = express();
  var port  = process.env.PORT || 3700
  
  var io = require('socket.io').listen(app.listen(port));
  io.on('connection', function (socket) {
      console.log("Socket connected on port " + port)
  
      socket.on('send', function (data) {
          console.log("WAFFLES")
      });
  });
  console.log('The magic happens on port ' + port);
  
  require('./app/routes.js')(app, io);
  </code></pre>
  
  <p>// app/routes.js</p>
  
  <pre><code>module.exports = function(app, io){
  
    app.get('/', function(req, res){
  
      io.on('connection', function (socket) {
          console.log("Hello from the route!")
          socket.emit('send', {message: 'urdum'})
      });
  
      res.render('index')
    })
  }
  </code></pre>
  
  <p>So in this instance, I want to be able to go into the / route, see "Hello from the route" and then "WAFFLES" logged to the console after emitting the "send" event. Instead I get absolutely nothing.</p>
  
  <p>I've tried to pass in "io" via app.set('socketio', io). But no matter what, nothing works.</p>
  
  <p>I've also tried emitting the event within the route without the io.on('connection') and simply just doing </p>
  
  <pre><code>io.emit('send' ...)
  </code></pre>
  
  <p>OR</p>
  
  <pre><code>io.sockets.emit('send' ...)
  </code></pre>