Socket.io: Namespaces, channels & co

旧街凉风 提交于 2019-11-28 16:42:42

You could be using rooms so you would do the following to emit to everybody in a room

io.sockets.in('a').emit('inA', 'foo')

Then to emit to everybody you can use

io.sockets.emit('everyone','bar');

You can also use namespaces as well:

io.of('/b').emit('inB', 'buzz');

To emit to everyone except the user that triggered you would use:

io.sockets.broadcast.emit("hello");

[edit] Here is a more detailed answer:

The idea behind name-spacing is that it is handled separately from the other namespaces (even global). Think of it as if it was an entirely new socket.io instance, you can run new handshakes, fresh events, authorizations, etc without the different namespaces interfering with each other.

This would be useful for say /chat and /tracking where the connection event would have very different logic

Socket.io does all the work for you as if it is two separate instances, but still limits the information to one connection, which is pretty smart.

There might be a workaround in which you can broadcast to all the namespaces (example below). However in short you shouldn't be doing this, you should be using rooms.

for (var nameSpace in io.sockets.manager.namespaces){
  io.of(nameSpace).emit("messageToAll", message);
}
Marwen Trabelsi

This is a template application you can use (works for 9.16; not tested on 1.x but it should work):

var namespaces = [
    io.of('/ns1'),
    io.of('/ns2'),
    io.of('/ns3')
];

for (i in namespaces) {
    namespaces[i].on('connection',handleConnection(namespaces[i]));  
}

function handleConnection(ns) {
   return function (socket){ //connection
   console.log("connected ");
   socket.on('setUsername',setUsernameCallback(socket,ns));                       
   socket.on('disconnect', disconnectCallback(socket,ns));                        
   socket.on('messageChat',messageChatCallback(socket,ns));
   socket.on('createJoinRoom',createJoinRoomCallback(socket,ns));  

  };
}

function disconnectCallback(socket,ns) {
    return function(msg){
    console.log("Disconnected ");
    socket.broadcast.send("It works!");
  };
}

You could write other handles by yourself :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!