Alexander Mills
Alexander Mills

Reputation: 100320

Retrieving socket.io connection that pertains to HTTP request

I am using socket.io with Express.

Say the user hits the canonical route /, and the request gets routed to:

app.get('/',function(req,res,next){

   var msg =...;
   socket.emit('channel',msg); //how do I find the right socket object that pertains to this HTTP request?

});

what is the best way to find the socket connection that pertains to this HTTP request with socket.io?

My best guess is to mark sockets with a session id upon the socket connection being authenticated, and then retrieve them later (in a place like the function above) with the same session id? The session id is available on the request object in Express middleware.

Also I have this code binding socket.io to the Express server:

var server = http.createServer(app).listen(port);
var io = require('socket.io').listen(server);  //we need to bind socket.io to the http server

and my own socketio module, I do this:

var cookie = require("cookie");
var connect = require("connect");

var io = null;
var connectedUsers = {}; //hash of sockets with socket.id as key and socket as value

var init = function ($io) {

    if (io === null) {

        io = $io;

        io.use(function (socket, next) {
            var handshakeData = socket.request;

            if (handshakeData.headers.cookie && handshakeData.cookie) {

                handshakeData.cookie = cookie.parse(handshakeData.headers.cookie);

                //handshakeData.sessionID = connect.utils.parseSignedCookie(handshakeData.cookie['express.sid'], 'foo'); //pass session secret at end

                handshakeData.sessionID = cookie.parse(handshakeData.cookie['express.sid'], 'foo'); //pass session secret at end

                if (handshakeData.cookie['express.sid'] == handshakeData.sessionID) {
                    return next('Cookie is invalid.', false);
                }

            } else {
                return next('No cookie transmitted.', false);
            }

            console.log('user with socket.id=', socket.id, 'has authenticated successfully.');
            return next(null, true);

        });


        io.on('connection', function (socket) {
            console.log('a user connected - ', socket.id);

            connectedUsers[socket.id] = socket;

            socket.on('chat message', function (msg) {
                console.log(socket.id, 'says', msg);

                socket.emit('chat message', 'hey baby hey - I am '.concat(socket.id));
            });

            socket.on('disconnect', function () {
                console.log('user disconnected -', socket.id);
                connectedUsers[socket.id] = null;
            });
        });
    }
    else if ($io != null) {
        throw new Error('tried to re-init socketio.js by passing new value for io in?? what are you doing.')

    }
    else {

    }


    return {

        addListener: function(){

    }


};

module.exports = init;

Upvotes: 4

Views: 1742

Answers (1)

victor
victor

Reputation: 70

You have to create an array or json objects and save the socket objects when they connect to the server. Just like this:

var clients = {}
io.on("connection", function(socket){
   socket.on("login", function(data){
       clients[data.user] = socket;
   });
});

Then when you receive the https request the client pass the user as a parameter and you look at the object clients:

clients[user].emit(...)

Upvotes: 1

Related Questions