Kwang Kwang - 3 months ago 12
Node.js Question

socket.io setting for expressjs

I just tried to use 'Socket.io'
For initial setting, document says the code below

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(80);


and this is my original code.

var app = require('express')();
app.listen(80);


what's the difference between two?
Specifically 2 questions.


  1. require('http').Server(app) => Why do I need to put app as a argument of Server?

  2. why do i have to use server.listen() instead of app.listen() ??



I looked up the document of node.js and express.js but can't understand...

I'll be really appreciated for your full explanation...

Answer

Your original code is using Express to create the HTTP server for you. The reason you can do app.listen() is because it is also returning the server instance so it's essentially a convenience method for:

app.listen = function() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
}; 

The initial setting in your example is shorthand for:

var http = require('http');
var server = http.createServer();
var express = require('express');
var app = express();
var socketio = require('socket.io'); 
server.on('request', app);
var io = socketio(server); 

server.listen(80);

In this example you are creating a new connection server for web sockets and integrating it into the http server yourself. The reason you are passing app as an argument of Server is so that the express app takes precedence over the socket server for typical http requests.

Comments