Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io sharing socket data between namespace

I want to know how to share data being set in a socket in one namespace and access it on another namespace?

I'm fully aware that i can attach data to the socket object itself.Problem arise when i attach the data on one namespace and try to access it on another namespace.

Below demonstrate the problem

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

module.exports.init = function( server ) {

    io = io.listen( server );

    io.of( '/chatSystem' ).on( 'connection', function( socket ) {
        /*handling set nickname event*/
        socket.on( 'set.name', function( data ) {
            /*attach nickname key to this socket*/
            socket.nickname = data.name;
            socket.broadcast.emit( 'user.entered', data );
        });
    });

    io.of( '/chatUser').on( 'connection', function( socket ) {
        /*handling client event socket.send*/
        socket.on( 'message', function( data ) {
            data = JSON.parse( data );
            data.nickname = socket.nickname; // <--- this is undefined

            /*send to all connected client( broadcast will not send message to socket that created the message)*/
            socket.broadcast.send( JSON.stringify( data ) );
            data.type = 'myMessage';

            /*manually send back the message to the socket that created the message*/
            socket.send( JSON.stringify( data) );
        });
    });
};

Is there a way to fix this?

like image 358
slier Avatar asked Apr 23 '15 13:04

slier


1 Answers

This might be a bit late but i just stumbled on a simpler solution and thought i would share for future investigators.

with socket > 1.0, you can store shared data in the socket's client object. It seems to still be shared among sockets

to use your example above

    /* attach nickname key to this socket */
    socket.client.nickname = data.name;
    /* In typescript with @types/socket.io */
    socket.client["nickname"] = data.name;

and for retrieval

    data.nickname = socket.client.nickname;
    /* In typescript with @types/socket.io */
    data.name = socket.client["nickname"];

Hope this helps someone out. I have been trying to find a solution all week and stumbled on this thread. An hour later, I found this alternative.

like image 130
Bayo O Avatar answered Sep 22 '22 20:09

Bayo O