Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sailsjs - what's the best way to track rooms at app level

sails.sockets.rooms() and sails.sockets.socketRooms() are both deprecated

In the doc:

This method is deprecated. Please keep track of your rooms in app-level code.

I am new to SailsJS.

Question 1: How could I get started with that? Where should I declare my room array or hash?

Question 2: How do I get the list of the clients connected?

like image 848
zabumba Avatar asked Oct 25 '16 14:10

zabumba


1 Answers

Here the way I did it. Hope this helps a little, although I am not confident it's perfect, BUT it worked for me. Feel free to suggest corrections, enhancements.

I declared a sails.rooms = {}; in the controller (Question 1) where I needed it most. (You can name it whatever you want.)

sails. gives it access across the application.

In the controller

  /**
   * Socket connection
   */
  connect: function(req, res) {
     // Check if it's socket connection
     if (!req.isSocket) { return res.badRequest(); } 

     // label the room to ROOM_NAME
     sails.sockets.join(req, ROOM_NAME);

     /**
      * Manage my `sails.rooms` HERE
      * e.g. 
      */
      if (!sails.rooms[ROOM_NAME]) {
        sails.rooms[ROOM_NAME] = {};
      }
      sails.rooms[ROOM_NAME][req.socket.id] = HUMAN_FRIENDLY_LABEL;
  }

I end up with a JSON that looks like this:

{
   { "room1" : 
     {
       "ksadj1234clkjnelckjna" : "john",
       "eroiucnw934cneo3vra09" : "marie"
     }
   },
   { "room2" : 
     {
       "kslaksdjfnasjdkfa9jna" : "antoine",
       "qweuiqcnw934cne3vra09" : "michelle"
    }
   }
}

In config/sockets.js, I manage disconnections

  afterDisconnect: function(session, socket, cb) {
    console.log(socket.id + " disconnected");
    /**
     * Manage sails.rooms HERE
     * e.g.
     */
    for (r in sails.rooms) {
      delete sails.rooms[r][socket.id];
      //
      // YOUR CODE
      //
    }

    return cb();
  },

NOTE: that you can list the WebSockets in a certain room using sails.io.sockets.in(ROOM_NAME). This should also help to purge the sails.rooms from disconnected sockets.

like image 137
zabumba Avatar answered Nov 20 '22 10:11

zabumba