Skip to content
Advertisement

How to add rooms in Node.js with Socket.io?

I have been following up many articles to learn making chat application with Node.js and Socket.io. Everything is clear and I can make an application moving messages from client to server and emitting to all etc but only one thing is not clearing and cannot figure this out.

How can I add rooms to io.sockets.manager.room?

What is the code to add rooms to sockets.manager? The most simple and thorough article I found is http://udidu.blogspot.com/2012/11/chat-evolution-nodejs-and-socketio.html but after a long struggle I still could not find where the author adds new rooms to server.

Advertisement

Answer

io.sockets.manager.room

returns list of rooms. Your question is not correct. You don’t add rooms to io.sockets.manager.room instead you make a socket join a room and that room is added to io.sockets.manager.room.

To make a socket join a room use this:

io.sockets.on('connection', function(socket){
    var room = 'Your room name';
    socket.room = room;
    socket.join(room);
    socket.on('disconnect', function(){
        socket.leave(socket.room);
    });
});
Advertisement