Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to emit an event in socket.io from the routes file?

This is my app configuration

app.js

//SERVER
var server = app.listen(3000, function(){
    console.log("Express server listening on port %d in %s mode", app.get('port'),
    app.settings.env);
});
//SOCKET.IO
var io = require('./socket.io').listen(server)

/socketio

var socketio = require('socket.io')

module.exports.listen = function(app)
{
    io = socketio.listen(app);
    io.configure('development',function()
    {
            //io.set('transports', ['websocket', 'xhr-polling']);
            //io.enable('log');
    });
    io.configure('production',function()
    {
        io.enable('browser client minification');  // send minified client
        io.enable('browser client etag');          // apply etag caching logic based on version number
        io.set('log level', 1);                    // reduce logging
        io.set('transports', [                     // enable all transports (optional if you want flashsocket)
            'websocket'
          , 'flashsocket'
          , 'htmlfile'
          , 'xhr-polling'
          , 'jsonp-polling'
        ]);
    });
    io.sockets.on('connection', function (socket)
    {
        console.log("new connection: "+socket.id);
        socket.on('disconnect',function(){console.log("device "+socket.id+" disconnected");});

        socket.emit('news', { hello: 'world' });
        socket.on('reloadAccounts',function(data)
        {
            var accounts=['account1','account2']
            socket.emit('news',accounts)
        });
    });
    return io
}

/routes

    exports.newAccount=function(fields,callback)//localhost:3000/newAccountForm
    {
//... bla bla bla config db connection bla bla bla
            db.collection('accounts').insert(fields,function(err,result)
            {
                if(err)
                {
                    console.warn(err);
                    db.close();
                    return callback(err,null);
                }else{
                    if(result)
                    {
                        db.close();
                        return callback(null,result);
                                socket.emit('new account created',result) // i want to emit a new event when any user create an account

                    }else{
                        db.close();
                        return callback('no se consigue resultado',null);
                    }
                }
            })
        });
    }

How to emit an event in socket.io from the routes file?

like image 797
andrescabana86 Avatar asked Nov 03 '22 17:11

andrescabana86


1 Answers

First you need to decide that what socket you want to send the new info. If it's all of them(to everyone connected to your app), it would be easy, just use io.sockets.emit:

In the ./socket.io file you add exports.sockets = io.sockets; somewhere after io = socketio.listen(app);. Then in the routes file, you can emit like this:

var socketio = require('./socket.io');
socketio.sockets.emit('new account created', result);

If you know the socket id that you want to send to, then you can do this:

var socketio = require('./socket.io');
socketio.sockets.sockets[socketId].emit('new account created', result);

You can also select the socket by express session id:

First you need to attach the session id to the socket on authorization:

io.set('authorization', function (data, accept) {
    // check if there's a cookie header
    if (data.headers.cookie) {
        // if there is, parse the cookie
        data.cookie = cookie.parse(data.headers.cookie);
        // note that you will need to use the same key to grad the
        // session id, as you specified in the Express setup.
        data.sessionID = data.cookie['express.sid'];
    } else {
       // if there isn't, turn down the connection with a message
       // and leave the function.
       return accept('No cookie transmitted.', false);
    }
    // accept the incoming connection
    accept(null, true);
});

Then you can select sockets with the session id:

var socketio = require('./socket.io');
var sockets = socketio.sockets.forEach(function (socket) {
    if (socket.handshake.sessionID === req.sesssionID)
        socket.emit('new account created', result);
});

You can also query your session store and using the method I described above, emit the event to sockets with sessionId that matched your query.

like image 107
Farid Nouri Neshat Avatar answered Nov 09 '22 09:11

Farid Nouri Neshat