Using Socket.io With Express 3.x
Back in Express 2.x, you would create an express object:
and then configure your socket.io object to listen along with the express app:
then tell the express app to listen on a port:
One of the first changes in Express 3.x is that express.createServer() has been deprecated. If you try to use it, you will receive the following message when you start your app:
Warning: express.createServer() is deprecated, express applications no longer inherit from http.Server, please use:
var express = require("express");var app = express();
Ok, no big deal, let's just do exactly what it says:
Want to master Node.js? Try my highly-rated online course Learn Node.js by Example. Click here to get 50% off on screencasts, interactive projects, and more!
However, you now have a very different object stored as 'app' then you did in Express 2.x. Before, app was derived from the HTTP server object type, which is what socket.io expects to be passed in its listen() method:
If you pass this new app object in, while no error will be thrown, the socket.io connections will not succeed. On launching your app, you will even get a helpful message:
Socket.IO's `listen()` method expects an `http.Server` instance as its first parameter. Are you migrating from Express 2.x to 3.x?
Which is a pretty good clue that you need to make some minor adjustments. Here's how to fix things.
First, create an HTTP server object from your new Express 3.x app object:
Now, pass this server object to socket.io instead:
Finally, you will need to invoke the server object to start listening on a port, rather than the app object, since the server object is what socket.io is linked with. This will work fine, but is against the standard Express 3.x convention:
Keep an eye out, as you this is a change you will have to make for the time being, especially when adding socket.io into existing Express 3.x apps.
Happy Noding!