Question

Okay, I have a simple test server set up using socket.io in node.js. My goal is to run the same server on a few different ports to test some load balanced conditions and synchronization tests.

Here is what the server looks like:

var app = require('http').createServer(handler),
      io = require('socket.io').listen(app),
      fs = require('fs'),
      port = process.argv[1]; // listen on port number passed via command line

app.listen(port);

function handler (req, res) {
   console.log('request', {remotePort: req.connection.remotePort, remoteAddress: req.connection.remoteAddress, url: req.url});
   // how do I pass the port number here?
   fs.readFile(__dirname + '/chat.html',
         function (err, data) {
            if (err) {
               res.writeHead(500);
               return res.end('Error loading chat.html');
            }

            res.writeHead(200);
            res.end(data);
         });
}

io.sockets.on('connection', function (socket) {
   // do chatty stuff
});

The question is: what is the easiest way to get the port number into chat.html (see comment in code above)? Is there a way to do this with node or fs? Do I need to Express set up with templates?

Wonder what node will let me do with the query string; could I just stick the port in there and pick it out with jQuery once the page loads?

Thanks, in advance!

Was it helpful?

Solution

html is for static contents. so you can not use for dynamic contents. so easiest way is using templates like ejs, jade and jquery template.

but you don't want you can change contents from chat.html

function(err, data) {
  data = data.replace() // like this
}

I'm not recommend this way.

OTHER TIPS

This is an old question, but decided to answer it with a more suiting answer still.

Because you're listening on the same port on both the http and socket.io, you can just change the script on the client to connect to the same address as the webpage was loaded, like so:

var socket = io.connect(window.location.href);

If the server was just a normal websocket server, you could do instead this:

var socket = new WebSocket(window.location.href.replace('http', 'ws'));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top