简体   繁体   中英

emit a message to all sockets of one specific user in node.js

I am currently using Node.js and it's working very well, for each user I save sockets. also saving all browser tab sockets ID. I mean each tab has a unique socket. so a unique user have multiple sockets. Here is what I do.

usersObj = {};

io.sockets.on( 'connection', function( socket ) {
    socket.on("new user", function( data, callback ) {


        if ( data.id in usersObj ){ // if user is in usersObj, save it's new socket.id

            usersObj[data.id].sockets_ids.push( socket.id );

            // how to send a message to all sockets of a specific user
            // usersObj[data.id].sockets.socket.emit( "hi", { data: "Hi!" } ); this does not work.

        } else { // if user is not in usersObj, make a new object and save it's socket.

            usersObj[data.id] = {
                "sockets_ids" : [ socket.id ] // array for all sockets id of this user
            }

        }
    });
});

Now userObj for user with ID 10, and user with ID 11, is this:

usersObj = {
    10 = {
        sockets_ids = [
            asdf9877687sdfasdf,    // sample socket ID for browser tab 1
            459djhfskdhjfasd8f,    // sample socket ID for browser tab 2
            oewurwoer845935739     // sample socket ID for browser tab 3
        ]

    },
    11 = {
        sockets_ids = [
            xcdf987sdfsddfasdf,    // sample socket ID for browser tab 1
            ty9djhfskdhjf45344,    // sample socket ID for browser tab 2
            sawurwoer84593xcvx     // sample socket ID for browser tab 3
        ]

    },

}

Now I want to emit a message Hi! to all sockets belongs to user with ID 10. So I should get sockets by their ID which is in user's sockets_ids array and emit to that socket my message.
How can I do that?
This is completely wrong and does not work.
usersObj[data.id].sockets_ids.socket.emit( "hi", { data: "Hi!" } );

Thanks in advance.

You need to loop through the sockets_ids like so:

usersObj[data.id].sockets_ids.forEach(function(id){
    io.sockets.socket(id).emit("hi", { data: "Hi!" });
});

Also you should consider storing the actual socket object instead of the socket.id, as the method utilized above is an internal method of socket.io, and thus is not reliable. See here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM