3
votes

I have socket id of each connected user stored in my database. When any user posts a comment or status, I want to broadcast the same to all his/her connections using socket id stored in my database.

I can emit the message to individual client using his/her socket id by using io.sockets.connected[ socket.id ].emit('privateMsg', 'Hello! How are you?');

But how do I emit the same to the array of socket id which i have generated using select query from my database.

2
Did you maintain socket id and user id array on your server.js. As far as i know Whenever you refresh or loads page in new tab it creates new socket id - Mangesh Sathe
Yes, I do maintain socket id on my server.js. Whenever the page loads, i am updating the socket id for that particular user - TechMech
socketsids.forEach(function(socketid){io.to(socketid).emit(...)} - laggingreflex

2 Answers

6
votes

You can use concept of rooms. Whenever a socket connection arrives, join the connections to a room. And on disconnect, remove the socket from the room.

socket.on('connection', function () {
     socket.join('room1');
});  

socket.on('disconnect', function () {
     socket.leave('room1');
});

Now when you want send messages to sockets connected on a room, you can broadcast it to room.

socket.broadcast.to('room1').emit('eventName', data);
1
votes

You could dynamically create a room for each socket that connects and emit to it without having to loop over the entire array every time. Like so:

socketids.foreach(function(socketid){io.sockets.connected[socketid].join(sendingSocket.id);});

Then you can emit to those sockets from your sending socket by doing the following:

sendingSocket.to(sendingSocket.id).emit('publicMessage', 'Hello! How are you?')

As a side-note, I don't think keeping socket ids that change in a database is the best approach, since they have no persistence at all. You may want to try to find a better identifier for your database.