2

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?

1 Answer 1

5

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.

1
  • Great, many thanks for the reply! It makes total sense. My confusion was that I thought that the event should go through the other NS first before finally be emitted to the clients.
    – Nick
    Commented Oct 9, 2018 at 14:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.