title: Express + Socket.IO + RabbitMQ (node-amqp)
body: <p>I'm having a hard time putting all these three together, probably because I'm not getting properly the concept of routing with Express.</p>
  
  <p>I have a RabbitMQ queue with event updates. We can recognize these events by their id. So I want to get on a given page about an event, just the updates corresponding to its id.</p>
  
  <p>Queue: 1316, 1539, 3486, 3479, 1316, 3890, 3479, ... -> Feed from the DB indefinitely.
  www.example.com/event/1316 -> Gets from the queue just messages with id 1316
  www.example.com/event/3479 -> Gets from the queue just messages with id 3479</p>
  
  <p>My code works good when I load the first event, but when I load the second one in a different window, it gets messages from both events, and if I load a third one, guess right, it gets messages from the three ids.</p>
  
  <p><strong>app.js</strong></p>
  
  <pre><code>var express = require('express')  
  , http = require('http');
  var app = express();
  var server = http.createServer(app);
  var io = require('socket.io').listen(server, { log: false });
  require('./io')(io);
  
  var amqp = require('amqp');
  var rabbitMQ = amqp.createConnection({ host: 'localhost' });
  
  rabbitMQ.on('ready', function() {
    console.log('Connected to RabbitMQ');
    io.sockets.on('connection', function (socket) {
      console.log('Socket connected: ' + socket.id);
      rabbitMQ.queue('offer', { autoDelete: false, durable: false, exclusive: false }, function(q) {    
        q.bind('#'); // Catch all messages    
        q.subscribe(function (message) {
          obj = JSON.parse(message.data.toString());
          //socket.broadcast.to(obj.id).emit('message', obj);
          io.sockets.in(obj.id).emit('message', obj);
        });
      });
    });
  });
  
  var routes = require('./routes')
  , event = require('./routes/event');
  
  app.get('/', routes.index);
  app.get('/event/:id', event.index);
  
  server.listen(app.get('port'), function(){
    console.log("Express server listening on port " + app.get('port'));
  });
  </code></pre>
  
  <p><strong>io.js</strong></p>
  
  <pre><code>var socketio = function (io) { 
    if (!io) return socketio._io;  
    socketio._io = io;
  } 
  
  module.exports = socketio;
  </code></pre>
  
  <p><strong>routes/event.js</strong></p>
  
  <pre><code>var io = require('../io')();
  
  exports.index = function(req, res) {
    io.sockets.on('connection', function (socket) {
      socket.join(req.params.id);
    });
    res.render('event', { title: 'Event' });
  };
  </code></pre>
  
  <p>Thanks!</p>