Mean.io framework with socket.io Mean.io framework with socket.io express express

Mean.io framework with socket.io


I also faced the same issue and took me about a week to finally get it right. I'll try to explain what I did:

app.js

In this file, I just invoke the code that creates and sets up a socket.io object for me, which is then passed to the routes module.

'use strict';/* * Defining the Package */var Module = require('meanio').Module;var MeanSocket = new Module('chat');/* * All MEAN packages require registration * Dependency injection is used to define required modules */MeanSocket.register(function(app, http) {    var io = require('./server/config/socketio')(http);    //We enable routing. By default the Package Object is passed to the routes    MeanSocket.routes(io);    return MeanSocket;});

server/config/socketio.js

This file simply configures the socket.io object. Please note that I had to upgrade meanio module to version 0.5.26 for this work, as http object (express server) is not available in older meanio versions. Moreover, in case you want to use ssl, you can inject https instead of http.

'use strict';var config = require('meanio').loadConfig(),    cookie = require('cookie'),    cookieParser = require('cookie-parser'),    socketio = require('socket.io');module.exports = function(http) {    var io = socketio.listen(http);    io.use(function(socket, next) {        var data = socket.request;        if (!data.headers.cookie) {            return next(new Error('No cookie transmitted.'));        }        var parsedCookie = cookie.parse(data.headers.cookie);        var sessionID = parsedCookie[config.sessionName];        var parsedSessionID = cookieParser.signedCookie(parsedCookie[config.sessionName], config.sessionSecret);        if (sessionID === parsedSessionID) {            return next(new Error('Cookie is invalid.'));        }        next();    });    return io;};

routes/chat.js

Finally, use the routes file to define the socket events, etc.

'use strict';// The Package is passed automatically as first parametermodule.exports = function(MeanSocket, io) {    io.on('connection', function(socket) {        console.log('Client Connected');        socket.on('authenticate', function(data, callback) {        });    });};

Hope this helps!


The simplest way would be to install the socket package...

mean install socket