1

Its a duplicate question, though I want to ask it for more clarification on it.
I want to create a private chat using socket.io. While googling for it, I found 2 solutions:

  1. Use an array to store the active user list
  2. Use room concept

Suppose my app has millions of active users.
Here's what I want: I have my friend list in mysql db, and when I log in, I want all friends and their status (active or not).

case 1. If I use an array to store all active users, then it works pretty well, but is this a good way to store all users who are connecting to my app in an array?

case 2. If I use the room concept where each of users friend have a unique roomid, then whenever a user logs in, he has to join all those roomid. It also worked for me, but in this case, how do I know if my friend is active or not?

I want to know which of this solution will work for my app which will have millions of user, or is there any other way to solve this.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
pitu
  • 822
  • 3
  • 11
  • 35

1 Answers1

2

I would use a third solution :

  • sets the user to each socket
  • look at the list of client sockets in a room any time you need to list the users in the room

If you're using socket.IO pre 1.0, then you can use io.sockets.clients(roomName) to get the sockets in a room.

With socket.IO 1.0, it's not really clear what will be the cleanest solution to list sockets connected to a room :

For now here's a workaround function :

function roomSockets(roomId) {
    var clients = io.sockets.adapter.rooms[roomId],
        sockets = [];
    for (var clientId in clients) sockets.push(io.sockets.connected[clientId]);
    return sockets;
}

Note that it might not work with all adapters so it's, at best, a workaround.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • i used var clients = io.sockets.clients('room1'); console output : [object Object] how to print all the client list – pitu Jun 05 '14 at 12:16
  • Use `io.sockets.clients('room1').forEach(function(s){ console.log(s) });` – Denys Séguret Jun 05 '14 at 12:22
  • Example : [Here's how I was listing users in a room in an old version of my chat](https://github.com/Canop/miaou/blob/c21bfa3481b75ef0750ed09905e5e51c1247e096/libs/ws.js#L193) – Denys Séguret Jun 05 '14 at 12:23
  • ya i am doing in he same way, the output for that is [object Object] how to parse the object, i want data from this array – pitu Jun 05 '14 at 12:27
  • A solution is to use [set](https://github.com/Canop/miaou/blob/c21bfa3481b75ef0750ed09905e5e51c1247e096/libs/ws.js#L47) and [get](https://github.com/Canop/miaou/blob/c21bfa3481b75ef0750ed09905e5e51c1247e096/libs/ws.js#L194). – Denys Séguret Jun 05 '14 at 12:34