Socket.IO - Rooms

Within each namespace, you can also define arbitrary channels that sockets can join and leave. These channels are called rooms. Rooms are used to further-separate concerns. Rooms also share the same socket connection like namespaces. One thing to keep in mind while using rooms is that they can only be joined on the server side.

Joining Rooms

You can call the join method on the socket to subscribe the socket to a given channel/room. For example, let us create rooms called 'room-<room-number>' and join some clients. As soon as this room is full, create another room and join clients there.

Note − We are currently doing this on the default namespace, i.e. '/'. You can also implement this in custom namespaces in the same fashion.

var app = require('express')();
var http = require('http').Server(app);
var io = require('')(http);
app.get('/', function(req, res){
var roomno = 1;
io.on('connection', function(socket){
   //Send this event to everyone in the room."room-"+roomno).emit('connectToRoom', "You are in room no. "+roomno);
http.listen(3000, function(){
   console.log('listening on localhost:3000');

Just handle this connectToRoom event on the client.

<!DOCTYPE html>
   <head><title>Hello world</title></head>
   <script src="/"></script>
      var socket = io();
         document.body.innerHTML = '';

Now if you connect three clients, the first two will get the following message −

You are in room no. 1

Leaving a Room

To leave a room, you need to call the leave function just as you called the join function on the socket.

For example − To leave room 'room-1',

Kickstart Your Career

Get certified by completing the course

Get Started