Mean.io framework with socket.io

前端 未结 2 1023
野趣味
野趣味 2021-01-07 04:33

How to use socket.io in Mean.io stack?

First of all, Mean.io changes their folder structure very regularly.. So my question is where is the best place to configure s

相关标签:
2条回答
  • 2021-01-07 05:08

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

    mean install socket
    
    0 讨论(0)
  • 2021-01-07 05:12

    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!

    0 讨论(0)
提交回复
热议问题