socketio节点为另一个名称空间发出

时间:2016-02-03 19:05:37

标签: node.js socket.io namespaces

我在Nodejs中使用socketIO,我正在处理两种类型的连接/命名空间,用户和设备,以便特定用户可以控制特定设备。

我为用户执行命名空间,为设备执行另一个命名空间。

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
});

是否有更好的设计模式来处理这种情况?

感谢。

2 个答案:

答案 0 :(得分:2)

您可以使用相同的实例来发出这些事件,就像这样。

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')
});

答案 1 :(得分:1)

我找到了一个很好的解决方案:

io.of('/devices').to(socket_id).emit('event_name');
相关问题