0

Using node and express, the below works just fine.

var app = express();

app.listen(app.get('port'), function() {
});

I assume that a server is created implicitly in the above construct.

When adding socket.io, I've seen the following being done.

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

app.listen(app.get('port'), function() {
});

What is the need for explicitly adding http.createServer(app) ? Won't the creation of an additional server mess up things ? Or put it other way, is it ok to create many more http.createServer(app) ?

4
  • Are you sure your second example is what you were seeing? I'd expect the second example to be server.listen(...) Commented Jul 28, 2014 at 3:46
  • Yes, it was server.listen(...). But it seems to make no difference. I tried both app.listen and server.listen - and they work fine. I'll keep the example as it is. Commented Jul 28, 2014 at 5:27
  • 1
    Are you sure they both work the same? I don't think socket.io will work right in the app.listen version. Commented Jul 28, 2014 at 14:05
  • You're right. They don't work the same for socket.io. (but work the same for say, sessions) Commented Jul 30, 2014 at 6:00

1 Answer 1

1

In either case, only one server is created. When using socket.io, you share the same http server between socket.io and express. Both libraries attach event listeners to the same server and have a chance to respond to the same events. They cooperate nicely because socket.io only handles relevant requests and express handles all the non-websocket requests. And just FYI you could not create more than one server on the same port. Only one process can listen on a TCP port at a time in the OS, so the second one would fail with an error when attempting to bind an in-use port.

Sign up to request clarification or add additional context in comments.

2 Comments

Understood that one server is in use. Thanks. But then, why doesn't var io = require('socket.io')(app); work ? Or how can we re-use the existing server ? Why the explicit need to do createServer(...) ?
Normally express creates the server implicitly and you don't need access to it or to create it. However, socket.io does really need explicit access to it so it can add event listeners, and express can optionally use a server instance you create and explicitly provide instead of implicitly creating it's own, for precisely this type of purpose. Another way to think of it is socket.io doesn't know about express, it knows about node core http.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.