Wednesday, February 8, 2017

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, lets 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 that we are currently doing this on the default namespace, ie, '/'. You can also implement this in custom namespaces in the same fashion.
To join a room you need to provide the room name as the argument to your join function call.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendfile('index.html');
});
var roomno = 1;
io.on('connection', function(socket){
  //Increase roomno 2 clients are present in a room.
  if(io.nsps['/'].adapter.rooms["room-"+roomno] && io.nsps['/'].adapter.rooms["room-"+roomno].length > 1)
    roomno++;
  socket.join("room-"+roomno);

  //Send this event to everyone in the room.
  io.sockets.in("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>
<html>
    <head><title>Hello world</title></head>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io();
      socket.on('connectToRoom',function(data){
          document.body.innerHTML = '';
          document.write(data);
      });
    </script>
    <body></body>
</html>
Now if you connect 3 clients, first 2 will get the message:
You are in room no. 1
Next one will get the message:
You are in room no. 2
3 clients connection to rooms

Leaving a room

To leave a room, you need to call the leave function just like you called the join function on the socket. For example, to leave room 'room-1',
socket.leave("room-"+roomno);

No comments:

Post a Comment