Reputation: 11389
All:
I am pretty new to Socket.io, right now, learning how to build a real time chat app with socket.io and Express.js, one question always confuses me so much is:
What is the relationship between Socket.io and Express.js?
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
I am trying to think socket.io as a library to provide a new communication protocol handler just like Express which can handle http and https. But why socket.io needs to bind to Express server in order to work, like in the code:
var io = require('socket.io')(server);
Could anyone give me a little detail what happened during the whole initialization:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
Thanks
Upvotes: 6
Views: 1756
Reputation: 707328
Every socket.io/webSocket connection starts with an HTTP request. Thus any webSocket server support needs an HTTP server that can field the initial request. That initial request contains an "upgrade" header which is a request to switch to the webSocket protocol so after that is processed, then the incoming HTTP/TCP connection is turned into a webSocket/TCP connection.
So, since webSockets are meant to co-exist with your webserver and even use the same incoming port (to make webSocket requests be same-origin requests and to use the default port 80) which means webSocket requests arrive on the exact same port and to the exact same server as your regular HTTP requests, then to support that scenario, socket.io must integrate with your web server (in this case Express) so that socket.io can install a handler in the Express http server so that any incoming http requests that happen to be incoming socket.io connections will be handled by the socket.io code rather than by your other Express handlers.
FYI, socket.io does not have to have Express around. If configured by itself, it will create it's own HTTP server, but doing so would require that HTTP server to be on a different host or port than your web server which is generally not the desired configuration.
So, socket.io can be configured multiple ways. You can pass it your Express instance in which case it will add a request handler to Express. You can pass it a plain http server in which case it will add a request handler to that server or you can pass it a port number and it will create its own http server. In all cases, it needs an http server in order to support incoming socket.io/webSocket connections.
Upvotes: 7