Mostafa Khattab
Mostafa Khattab

Reputation: 554

socketio node emit for another namespace

I am using socketIO in Nodejs, I am working over two types of connections/namespaces, users and devices, so that specific user can control a specific device.

I do namespace for users and another one for devices.

var users = io.of('/users').on('connection', function(socket){
   // here I need to emit an event for another namespace
});

var devices = io.of('/devices').on('connection', function(socket){
   // here's the namespace that contains the event I need to fire from users namespace
});

Is there a better design pattern for handling such a case ?

Thanks.

Upvotes: 1

Views: 1940

Answers (2)

Mostafa Khattab
Mostafa Khattab

Reputation: 554

I found a good solution:

io.of('/devices').to(socket_id).emit('event_name');

Upvotes: 1

BlaShadow
BlaShadow

Reputation: 11683

You could you the same instance to emit those events, something like this.

var users = io.of('/users');
var devices = io.of('/devices')

users.on('user_action', function(socket){
    devices.emit('device_custom_event');
});

devices.on('connection', function(socket){
    users.emit('device_connected')
});

Upvotes: 3

Related Questions