Mean.io framework with socket.io

∥☆過路亽.° 提交于 2019-12-01 00:50:29

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 parameter
module.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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!