Question

In the following snippet, a tutorial author shows how to alter the original tutorial to include an http server. Here's the snippet.

var http = require(‘http’),  
fs = require(‘fs’),  
io = require(‘socket.io’),  
index;  
fs.readFile(‘./chat.html’, function (err, data) {  
 if (err) {
    throw err;
 }
 index = data;
});
var server = http.createServer(function(request, response) {  
  response.writeHeader(200, {“Content-Type”: “text/html”});
  response.write(index);
  response.end();
}).listen(1223);
//and replace var socket = io.listen(1223, "1.2.3.4"); with:
var socket = io.listen(server); 

The code in the original tutorial didn't include the http server, and socket was defined as simply:

var socket = io.listen(1223, "1.2.3.4");

I noticed that he replaces the variable's content io.listen(1223, "1.2.3.4"); with server which doesn't include the ip (1.2.3.4) anywhere.

My Question:

  • What is the purpose/effect of the referenced IP address?
  • Why is it excluded when passing an http server to create the socket?
Was it helpful?

Solution

When you are listening on a port, you can optionally include the IP address of a specific interface to listen on. For example, you might have several network interfaces with several IP addresses, and only want your service running on one of them. A more common use case is that you only want your server accessible on localhost, so you might have it listen only on 127.0.0.1.

Now, when you call io.listen(server) where server is an existing Node.js HTTP server, Socket.IO isn't actually opening a new listening connection at all. This is a shortcut for Socket.IO to wrap its methods on the existing HTTP server. If you wanted to specify a specific interface address to listen on, you would need to do it where .listen() is called on the HTTP server, above where you call io.listen(server).

More info in the documentation for raw network sockets in Node.js: http://nodejs.org/api/net.html#net_server_listen_port_host_backlog_callback

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top