Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io - Emit to array of socket id

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.

like image 313
TechMech Avatar asked Oct 16 '25 17:10

TechMech


2 Answers

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);
like image 64
Saba Hassan Avatar answered Oct 18 '25 08:10

Saba Hassan


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.

like image 36
Sander Thomassen Avatar answered Oct 18 '25 07:10

Sander Thomassen