Socket.io: how to join and leave rooms

I am trying to learn Socket.io by creating a set of dynamically created chats that come out of “connected” and “disconnected” messages when users log in and out. After looking at a couple of questions, I put together something functional, but most of the answer is related to people who admit that they have cracked the answers, and I noticed there is a more general and recent discussion about the correct way to do this on Socket. io repo (especially here and here )

Since I'm such a newbie, I don’t know if the work below is an acceptable way to do something or just happens by accident, but it will cause performance problems or lead to too many listeners. If there is an ideal and formal way to join in and leave rooms that feel less awkward than that, I would love to know 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
        });  
      })
  });
+4
source share
1 answer

Socket.IO : recently released v2.0.3

Regarding inputs / outputs [read documents.]

To join , the 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');
  }
})

, 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');
  }
})

,

,

( "" socket.rooms )

 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. 
   */
 });

, :

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

Socket.IO Emit Cheatsheet

0

Source: https://habr.com/ru/post/1625193/


All Articles