Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io: How to correctly join and leave rooms

I'm trying to learn Socket.io by building a set of dynamically created chatrooms that emit 'connected' and 'disconnected' messages when users enter and leave. After looking at a couple of questions I've put together something functional but most of the response linked are from people who admit they've hacked together answers and I've noticed there's a more general - and recent - discussion about the right way to do this on the Socket.io repo (notably here and here)

As I'm such a novice I don't know if the work below is an acceptable way to do things or it just happens to incidentally function but will cause performance issues or result in too many listeners. If there's an ideal - and official - way to join and leave rooms that feels less clunky than this I'd love to learn about it.

Client

var roomId = ChatRoomData._id // comes from a factory


function init() {

    // Make sure the Socket is connected
    if (!Socket.socket) {
        Socket.connect();
    }

    // Sends roomId to server
    Socket.on('connect', function() {
        Socket.emit('room', roomId);
    });

    // Remove the event listener when the controller instance is destroyed
    $scope.$on('$destroy', function () {
        Socket.removeListener('connect');
    });

}

init();

Server

  io.sockets.once('connection', function(socket){
    socket.on('room', function(room){     // take room variable from client side
      socket.join(room) // and join it

      io.sockets.in(room).emit('message', {      // Emits a status message to the connect room when a socket client is connected
        type: 'status',
        text: 'Is now connected',
        created: Date.now(),
        username: socket.request.user.username
      });

      socket.on('disconnect', function () {   // Emits a status message to the connected room when a socket client is disconnected
        io.sockets.in(room).emit({ 
          type: 'status',
          text: 'disconnected',
          created: Date.now(),
          username: socket.request.user.username
        });  
      })
  });
like image 241
isdn Avatar asked Jan 20 '16 19:01

isdn


People also ask

How do you leave a socket room?

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

How many rooms can Socket.IO handle?

socket.io rooms are a lightweight data structure. They are simply an array of connections that are associated with that room. You can have as many as you want (within normal memory usage limits). There is no heavyweight thing that makes a room expensive in terms of resources.


1 Answers

Socket.IO : recently released v2.0.3

Regarding joining / leaving rooms [read the docs.]

To join a room is as simple as socket.join('roomName')

//:JOIN:Client Supplied Room
socket.on('subscribe',function(room){  
  try{
    console.log('[socket]','join room :',room)
    socket.join(room);
    socket.to(room).emit('user joined', socket.id);
  }catch(e){
    console.log('[error]','join room :',e);
    socket.emit('error','couldnt perform requested action');
  }
})

and to leave a room, simple as socket.leave('roomName'); :

//:LEAVE:Client Supplied Room
socket.on('unsubscribe',function(room){  
  try{
    console.log('[socket]','leave room :', room);
    socket.leave(room);
    socket.to(room).emit('user left', socket.id);
  }catch(e){
    console.log('[error]','leave room :', e);
    socket.emit('error','couldnt perform requested action');
  }
})

Informing the room that a room user is disconnecting

Not able to get the list of rooms the client is currently in on disconnect event

Has been fixed (Add a 'disconnecting' event to access to socket.rooms upon disconnection)

 socket.on('disconnect', function(){(
    /*
      socket.rooms is empty here 
      leaveAll() has already been called
    */
 });
 socket.on('disconnecting', function(){
   // socket.rooms should isn't empty here 
   var rooms = socket.rooms.slice();
   /*
     here you can iterate over the rooms and emit to each
     of those rooms where the disconnecting user was. 
   */
 });

Now to send to a specific room :

// sending to all clients in 'roomName' room except sender
  socket.to('roomName').emit('event', 'content');

Socket.IO Emit Cheatsheet

like image 124
EMX Avatar answered Sep 20 '22 16:09

EMX