MEAN js & Socket.IO Integration Tutorial
Before We Start:
We are going to useĀ npmĀ andĀ mean.js. If youāre not already familiar with the MEAN stack or node.js, I suggest you take some time to catch up with this trendy and amazing platform for writing web applications.Ā
Installing socket.io:
Assuming you have already read the suggested article or have the mentioned packages installed on your machine, letās fire up a terminal window and create a new Mean.js project by running the following command
$ mkdir awesome-realtime-app && cd $_ $ yo meanjs
The generator will ask you the following questions(I have included my answers below, feel free to write down yours instead). Make sure that you include the default article module though, we will bind our realtime feature with that module.
[?] What would you like to call your application? Awesome Realtime Application [?] How would you describe your application? Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js [?] How would you describe your application in comma seperated key words? MongoDB, Express, AngularJS, Node.js [?] What is your company/author name? VEXXHOST [?] Would you like to generate the article example CRUD module? Yes [?] Which AngularJS modules would you like to include? ngCookies, ngAnimate, ngTouch, ngSanitize
Now just runĀ $ gruntĀ and you should have the app running on your localhost through port 3000. Letās include the awesome socket.io module from npm in our app. RunĀ $ npm install socket.io --save, this will install the package and add this in our package.json file.Ā
Binding socket.io With Express:
To initiate the server side socket connection, we need to integrate it with express.js. Letās start by opening up the fileĀ config/express.jsĀ in your favorite code editor and require the http and socket.io modules. I am adding this between line 6 and 7, right after the require of express āĀ
var express = require('express'), http = require('http'), socketio = require('socket.io'), .......
Now, letās tie it up with the app instance so that we can access it from anywhere in our app by taking advantage of the circular dependency of express.js. Go to the end of the file and add the following code right before the line where it readsĀ return app;-
// Attach Socket.io var server = http.createServer(app); var io = socketio.listen(server); app.set('socketio', io); app.set('server', server);
We are simply instantiating socket.io here and attaching our express server with it in the first 2 lines. In the next two, we are storing the socket.io and the server instance in our app container.
Easy, right? awesome! Just one more thing, open theĀ server.jsĀ file in the root directory and find where it readsĀ app.listen(config.port);Ā and replace it withĀ app.get('server').listen(config.port);. This will make sure we donāt mess up our http server instance of express.
Thatās all. Now we get to use it in our app. We will do something simple, we will notify all connected clients when a new article is created. To keep our code clean and easily maintainable, we can modularize the socket transmission and abstract it into a factory and there are many other techniques but for now we will just place it in our controller.
Open up the article server controller, open up the fileĀ app/controllers/articles.server.controller.jsĀ and find theĀ createĀ method. This method gets called when a new article is created. After the article is saved and there is no error we can notify everyone about it. So the following block of code goes inside the else block and right beforeĀ res.jsonp(article);Ā āĀ
var socketio = req.app.get('socketio'); // tacke out socket instance from the app container socketio.sockets.emit('article.created', article); // emit an event for all connected clients
This first parameter in the emit method is an event name and the second parameter is the data that will get sent along with the event. Thatās all our server needs to do.
Connecting socket.io With Angular:
So far, we have implemented socket.io on the server but that doesnāt mean it already works on the browser. We need to do that separately. We need listen for server emitted events from the browser.
We will use the angular component for Socket.io built byĀ btford. We can take advantage of bower for that. RunningĀ $ bower install angular-socket-io --saveĀ will install it and add it in our bower.json file.
Next we will to create an angular factory that will handle our websocket connection on the browser. Create a new fileĀ public/modules/core/services/socket.jsĀ and place the following code in it āĀ
'use strict'; //socket factory that provides the socket service angular.module('core').factory('Socket', ['socketFactory', function(socketFactory) { return socketFactory({ prefix: '', ioSocket: io.connect('http://localhost:3000') }); } ]);
We are making this a part of theĀ coreĀ module since we will want to use it across our app. Now we can use this socket connection inside our angular app. We forgot two vital things though, injecting the dependency and include necessary javascript files on our webpage. Open up the fileĀ app/views/layout.server.view.htmland add the following code before the closingĀ </body>Ā tag āĀ
<!-- Socket.io --> <script type="text/javascript" src="/socket.io/socket.io.js"></script> <script type="text/javascript" src="/lib/angular-socket-io/socket.min.js"></script>
Next up, dependency injection; Open the fileĀ public/config.jsĀ and appendĀ 'btford.socket-io'Ā at the of the list of dependencies array variable named āĀ var applicationModuleVendorDependencies.
Thatās it, now we have socket.io integrated with our angular app. But thatās just integration, letās see if it works. Open upĀ public/modules/articles/controllers/article.client.controller.jsĀ and on line 3 and 4 insert the Socket dependency. It should look something like āĀ
angular.module('articles').controller('ArticlesController', ['$scope', '$stateParams', '$location', 'Socket', 'Authentication', 'Articles', function($scope, $stateParams, $location, Socket, Authentication, Articles) {
We just added theĀ 'Socket'Ā in the list of arrays andĀ SocketĀ in the list of function parameters. Now, place the following code inside the controller āĀ
Socket.on('article.created', function(article) { console.log(article); });
Whatās happening here is, we are listening for theĀ 'article.created'Ā event through the socket and logging the article passed through the event in the console. To remind you, this is the event we emit when an article is created.













