Search code examples
socket.ionamespacesemit

socket.io emit message from one namespace to another


I'm trying to emit a message from one namespace to another (on connection). Bellow is some sample code with how I was trying to approach it.

[Server]

// Namespaces
var users_ns = io.of('/users');
var machines_ns = io.of('/machines');

// Attempt to receive the event on the socket
users_ns.on('connection', function(socket){
    socket.on('test', function(socket){
        console.log('socket test');
    });
});

// Attempt to receive the event on the namespace
users_ns.on('test', function(socket){
    console.log('namespace test');
});

// Emit an event to the 'users' namespace
machines_ns.on('connection', function(socket){
    users_ns.emit('test');
});

[Client1]

var socket = io('http://localhost/users');

[Client2]

var socket = io('http://localhost/machines');

Any idea why this doesn't work?


Solution

  • Your server code is correct, but some misunderstanding occurred.

    [server]

    // Namespaces
    var users_ns = io.of('/users');
    var machines_ns = io.of('/machines');
    
    // Attempt to receive the event on the socket
    users_ns.on('connection', function(socket){
        socket.on('test', function(){
            console.log('socket test');
        });
    });
    
    
    // Emit an event to the 'users' namespace
    machines_ns.on('connection', function(socket){
        users_ns.emit('test');
    });
    

    When you are broadcasting to users_ns sockets, this events received in client side, not in server sides. So this is correct client side code

    [Client1]

    var socket = io('http://localhost/users');
    socket.on('test',function(){ alert('broadcast received');});
    

    [Client2]

    var socket = io('http://localhost/machines');
    

    when one socket connect to machine namespace, all clients connected to users namespace will raise 'broadcast received' alert.