Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use socket.io with the latest mean.io?

I have fetched a copy of the latest Mean.io and noted quite a number of changes compared to the previous version I have been working with before. Now, what I am doing is creating a very basic chat application that uses socket.io with rooms. Following the basic setup in the Socket documentation I have to implement the following:

var app = require('express')()
  , server = require('http').createServer(app)
  , io = require('socket.io').listen(server);

server.listen(80);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

Where would I define the basic socket room setup?

socket.set("log level", 1);  
var people = {};  
var rooms = {};  
var clients = [];  
like image 814
Severin Avatar asked May 11 '14 07:05

Severin


People also ask

Can I use Socket.IO with spring boot?

So yes, you can use (on open-source Java implementation) of Socket.IO together with Spring Boot.

Does Socket.IO work on iOS?

Socket.IO is a framework that makes it easy to implement Socket and the available for iOS, Android, back-end and front-end.

Should I use Socket.IO in 2022?

With nearly 55k stars on GitHub and about 3 million downloads on npm weekly, Socket.IO is a great library to keep an eye on in 2022. The documentation is very straightforward, meaning even an inexperienced developer should be able to get started in little to no time.


2 Answers

You can set the socket.io to listen on your server on

/server/config/system/bootstrap.js

Require the socket.io module

var express = require('express'),
    appPath = process.cwd(),
    io      = require('socket.io');

Now set the socket.io to listen on your app

// Express settings
var app = express(); 
require(appPath + '/server/config/express')(app, passport, db);
io = io(app.listen(3000));    

return io;

Then you need to inject the socket.io object into your app on bootstrapDependencies() function.

function bootstrapDependencies() {
    ...

    // Register socket.io dependency
    mean.register('io', function() {
        return io;
    });
}

Mean.uses this project for its dependency injection https://www.npmjs.org/package/dependable

Finally you need to configure your app to listen on every socket connections probably you want to do these on your main app's router at

/server/routes/index.js

Sample connection handler

var io = require('meanio').io;

io.on('connection', function (socket) {
    // emit data to the clients
    socket.emit('news', { hello: 'world' });

    // event listeners
    socket.on('my other event', function (data) {
         // call your controller function here
         Controller.action(data);
    });
});

And more importantly, don't forget to setup socket.io on the client side.

// on '/server/views/includes/foot.html'
<script src='/socket.io/socket.io.js'></script>
<script>
    var socket = io();
</script>
like image 51
Mark Gutierrez Avatar answered Sep 21 '22 12:09

Mark Gutierrez


I've just responded to another SO post (Mean.io framwork with socket.io).

Note: I'm using mean.io v0.5.26 and socket.io v1.1.0.

Pasting my answer again, here.


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!

like image 40
Digitrance Avatar answered Sep 19 '22 12:09

Digitrance