title: NodeJS & Socket.io: Socket in a controller
body: <p>I have this code:</p>
  
  <p><strong>app.js:</strong></p>
  
  <pre><code>'use strict'
  var express = require('express')
    , http = require('http')
    , path = require('path')
    , app = express()
    , fs = require('fs')
    , engine = require('ejs-locals')
    , io = require('socket.io').listen(3872, {log:true})
    , connections = 0;
  app.set('port', 80);
  app.set('views', __dirname + '/views');
  app.engine('ejs', engine);
  app.set('view engine', 'ejs');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser('secret'));
  app.use(express.session());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
  
  fs.readdirSync('./controllers').forEach(function (controller) {
    if(controller.substr(-3) == '.js') {
      var route = require('./controllers/' + controller);
      route.controller(app);
    }
  });
  
  var server = http.createServer(app).listen(app.get('port'), function(){
    console.log('Server runs at port: ' + app.get('port'));
  });
  
  io.sockets.on('connection', function (socket) {
    connections++;
    console.log('New connection['+ connections +'] from ' + socket.handshake.address.address);
    socket.emit('pingPong');
  
    socket.on('disconnect', function() {
      connections--;
      console.log('Lost connection['+ connections +'] from ' + socket.handshake.address.address);
    });
  });
  </code></pre>
  
  <p><strong>/controllers/index.js</strong></p>
  
  <pre><code>var Model = require('../models/index');
  
  module.exports.controller = function(app) {
    app.get('/index', function(req, res) {
      res.redirect('/');
    });
  
    app.get('/', function(req, res) {
      res.render('index', { _: Model });
    });
  }
  
  socket.emit('hoi', {
      message: 'hi'
  });
  </code></pre>
  
  <p>Yeah, I get the error 'socket not defined' and I was actualy expecting that, but I don`t know how to access the socket var in a controller. Does anybody know how I can send sockets (with socket.io) in a controller?</p>