title: Socket.io across different Node.js routes
body: <p>I am building simple Node.js application that uses the Express Framework as well as Socket.io. I got stuck however trying to receive messages from the server across different express routes. Is there a way of receiving messages sent from one route to another route through the server? I've given a very simplified version of my code below:</p>
  
  <p><strong>app.js</strong></p>
  
  <pre><code>var express = require("express"),
      app = express(),
      http = require("http").createServer(app),
      fs = require("fs"),
      io = require("socket.io").listen(http);
  
  //Create a server
  var port = 9001;
  http.listen(port, function() {
    console.log("Server is running on port " + port);
  });
  
  //Set up routes
  var anotherPage = express.Router();
  anotherPage.route('/')
  .get(function(req, res, next) {
    res.sendFile('/AnotherPage.html', {root: './public'});
  });
  var someOtherPage = express.Router();
  someOtherPage.route('/')
  .get(function(req, res, next) {
    res.sendFile('/SomeOtherPage.html', {root: './public'});
  });
  
  //Set up static directories
  app.use(express.static(__dirname + "/public"))
      .use('/anotherpage', anotherPage)
      .use('/someotherpage', someOtherPage);
  
  io.sockets.on("connection", function(socket) {
    socket.on("send message", function(data) {
      socket.emit('return message', data);
    });
  });
  </code></pre>
  
  <h3>Inside public folder</h3>
  
  <p><strong>AnotherPage.html</strong></p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Sender&lt;/title&gt;
    &lt;script type="text/javascript" src="/socket.io/socket.io.js"&gt;&lt;/script&gt;
    &lt;script src="/anotherPage.js"&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;input id="input" type="text" /&gt;
    &lt;button onclick="sendMessage()"&gt;Submit&lt;/button&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><strong>anotherPage.js</strong></p>
  
  <pre><code>var socket = io.connect();
  
  function sendMessage() {
    socket.emit("send message", document.getElementById('input').value );
  }
  
  socket.on('return message', function(data){
    //Working
    console.log(data);
  });
  </code></pre>
  
  <p><strong>SomeOtherPage.html</strong></p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Receiver&lt;/title&gt;
    &lt;script type="text/javascript" src="/socket.io/socket.io.js"&gt;&lt;/script&gt;
    &lt;script src="/someOtherPage.js"&gt;&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    //TODO
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><strong>someOtherPage.js</strong></p>
  
  <pre><code>var socket = io.connect();
  
  socket.on('return message', function(data){
    //Not working
    console.log(data);
  });
  </code></pre>