V G V G - 6 months ago 14
Node.js Question

Socket io. Disable automatical joining a room identified by socket's id

In docs it is said: "Each Socket in Socket.IO is identified by a random, unguessable, unique identifier Socket#id. For your convenience, each socket automatically joins a room identified by this id."

I am wondering if there is an option to disable such feature.
My solution was:

io.on('connection', function (socket) {
leaveDefRoom(socket);
[...]
}

function leaveDefRoom(socket){
var room = socket.adapter.rooms;
for (var key in room){
if (key.charAt(0) == '/') {
socket.leave(key);
return;
}
}
}

Answer

In socket.io. Every time you emit event. socket.io send the event to the client in this room. If you remove user from the room, you cannot send this user messages. Even broadcast will not work.

Anyway, if you really want, you can leave this room, like any other room:

You can change socket.js file and disable this option:

https://github.com/socketio/socket.io/blob/master/lib/socket.js#L289

Socket.prototype.onconnect = function(){
  debug('socket connected - writing packet');
  this.nsp.connected[this.id] = this;
  // You have to remove this line below:
  this.join(this.id);   
  this.packet({ type: parser.CONNECT });
};