Category Archives: socketio

Socket.io how rooms work. And another chat example.

I continue to learn nodejs and socket.io. Today I will explain how do socket.io rooms work. Since for me it’s was quite difficult to understand in details what is it and how it work.

And yes still I’m consider myself not a pro in nodejs and socket.io. So this articles addressed to developers who is also just started their node way.

Ok Go. If we look at socket.io rooms docs  we will find the info how to use rooms but there’s no way to understand HOW it works.

In fact it’s quite straightforward. But let’s see it in details. And we need start from io object. What is it?

var io = require('socket.io')(http);

io_dump_with_markers

As you see io keeps info about all connected sockets. This means that you can access socket object if you know it’s ID.

var socket = io.sockets.connected[socketId];

So every socket has it’s own ID. It is generated for each new socket. Now let’s look at socket instance connected to one room.

socket_dump_with_markers

As you see default socket ID automatically added to rooms.  Therefore when we need to send message to sockets in certain room…

io.sockets.to(chat.room).emit('message', {message: "details"});

(as I can assume) Socket.IO just go through the socket.rooms of the connected sockets and selects sockets that has specified room id. Easy? I think yes. But I must admit I spent some time to get this point.

I hope this could be useful. Also looking ahead I published another nodejs chat example using socket.io you can check it out. This could be a good start point to create your own chat with blackjack.